Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php redirect to page with message

i want to redirect to a page and then display a message:

what i have is:

if (mysqli_affected_rows($link) == 1) 
{
   //succes         
    $message = 'succes';
    redirect_to('index.php');
}

on the index page i have:

if (!empty($message)) {
    echo '<p class="message"> '.$message.'</p>';
}

The redirect function is working fine:

function redirect_to( $location = NULL ) {
        if ($location != NULL) {
            header("Location: {$location}");
            exit;
        }
    }

But it won't display my message. Its empty.

like image 836
user1386906 Avatar asked Aug 16 '12 13:08

user1386906


1 Answers

By the time the redirect happens and the PHP script depicted by $location is executed, $message variable would have been long gone.

To tackle this, you need to pass your message in your location header, using GET variable:

header("Location: $location?message=success");

And

if(!empty($_GET['message'])) {
    $message = $_GET['message'];
// rest of your code

You could also have a look into sessions

session_start();
$_SESSION['message'] = 'success';
header("Location: $location");

then in the destination script:

session_start();
if(!empty($_SESSION['message'])) {
   $message = $_SESSION['message'];
   // rest of your code
like image 143
Andreas Wong Avatar answered Sep 21 '22 17:09

Andreas Wong