简体   繁体   中英

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. Structure is like this:

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

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

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.

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'])

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. 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?

<?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. I'd take a look at using a framework if I were you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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