14

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

What I have is:

//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. It's empty.

Dharman
  • 30,962
  • 25
  • 85
  • 135
user1386906
  • 1,161
  • 6
  • 26
  • 53

6 Answers6

31

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
muzudre
  • 7
  • 5
Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
4

Variables cease to exist after the script ends. Each separate request, each separate PHP script invocation is an entirely new context with no data from any other invocation.

Use sessions to persist data.

deceze
  • 510,633
  • 85
  • 743
  • 889
4

You can use sessions

//succes            
$_SESSION['message'] = 'succes';
redirect_to('index.php');

And on index

if (!empty($_SESSION['message'])) {
    echo '<p class="message"> '.$_SESSION['message'].'</p>';
    unset($_SESSION['message']);
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
2

Since you are running header("Location: {$location}"); the value of $location (set in the first file) is lost when index.php is loaded.

Jocelyn
  • 11,209
  • 10
  • 43
  • 60
2

you can avoid redirect function and use this code in the page

header("Location: $locationpage?message=success")

index.php

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

use the following code....

header("Location: index.php?message=success");

in index.php

$msg=$_GET['message'];
echo $msg;
Anoop
  • 993
  • 6
  • 16