简体   繁体   English

重定向到另一个页面并在php中显示消息

[英]Redirect to another page and show message in php

I'm trying after submitting a form, redirect from registration.php to index.php and show message there. 我正在尝试提交表单后,从registration.php重定向到index.php并在其中显示消息。 Structure is like this: 结构是这样的:

registration.php registration.php

class Registration 
{ 

...

public $messages = array();

...

if ($stmt->execute([$uid_new, $email_new, $pwd_1_hash])) {  
    $this->messages[] = 'success';
    header('Location index.php');
}

messages.php messages.php

if ($registration->messages) {
    foreach($registration->messages as $message) {
        echo "$message <br>";
    }

index.php index.php

<?php include 'messages.php'; ?>

However after redirect, message is not showing up. 但是,重定向后,消息未显示。 Where can be a problem here? 这里哪里有问题? Thanks. 谢谢。

You are using header that can redirect you on index.php page so your class object scope is finished if you want to use same message you must store your message in session and destroy session after print. 您正在使用可在index.php页面上重定向的标头,因此如果要使用相同的消息,则必须完成类对象范围,必须在会话中存储消息并在打印后销毁会话。

if ($stmt->execute([$uid_new, $email_new, $pwd_1_hash])) {  
    $this->messages[] = 'success';
     session_start();
     $_SESSION['errors'] = $this->messages;
    header('Location: index.php');
}

And on index page use 
$registration = $_SESSION['errors'];
if ($registration->messages) {
    foreach($registration->messages as $message) {
        echo "$message <br>";
    }

unset($_SESSION['errors']) 未设置($ _SESSION ['errors'])

Since you are redirecting inside your Registration class, you lose all data that is not saved in persistent storage (such as session) including your $messages array. 由于要在Registration类中进行重定向,因此会丢失所有未保存在持久性存储(例如会话)中的数据,包括$ messages数组。 I don't think your code is structured properly to handle a redirect like you want to. 我认为您的代码结构不正确,无法按需要处理重定向。 I'd suggest setting a session variable to hold your messages instead before redirecting. 我建议在重定向之前设置一个会话变量来保存您的消息。 Also, I don't know what is inside your errors.php file, but shouldn't it be messages.php? 另外,我不知道您的errors.php文件中包含什么,但是不应该是messages.php吗?

<?php

// Registration.php
class Registration
{
    public function save()
    {
        if ($stmt->execute()) {
            $_SESSION['messages'][] = 'success';
        }
    }
}

// messages.php
if (!empty($_SESSION['messages'])) {
    foreach($_SESSION['messages'] as $message) {
        echo "$message <br>";
    }
}

// index.php
include 'messages.php';

Also, I don't really endorse this style of code, its a little hacky in today's PHP ecosystem. 另外,我并不真正认可这种代码风格,在当今的PHP生态系统中,它有点hacker。 I'd take a look at using a framework if I were you. 如果您是我,我将考虑使用框架。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM