5

I'm trying to show a message after a successful redirect in my project, but can't find a really good way to do so. Right now I have a very simple and not really good solution which looks like this:

// Things happened:
$Alert = dangerMessage("Heyho, I am a message!");
header('refresh: 1.5 ; url = index.php');

My dangerMessage is a simple echo of a predefined Alertbox:

function dangerMessage($text) {
    return "<div class='alert alert-danger alert-dismissable fade show mt-4'>
    <a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a>".$text."</div>";
}

It simply shows a little box with text inside.

Anyway, like I said this is my "simple" solution right now, it works fine but it's not the best solution. I know that you should be putting a die(); or a exit(); after the header(), but my problem is that when I put them under my header() the page is just blank for 1.5 seconds, redirects, and shows no messagebox.

Is there a way to have a decent/good redirect that also shows my message?

Dharman
  • 30,962
  • 25
  • 85
  • 135
NakedPython
  • 920
  • 2
  • 7
  • 27

5 Answers5

7

An elegant and common approach is to use a flash message. This is basically a one-off session entry which is set in one request and is delivered in the next one, then instantly deleted. Consider the following example.

On the redirecting page, you set the flash message in the session object:

$_SESSION["flash"] = ["type" => "success", "message" => "You are great!"];

On a target page, check if there’s a flash message. If so, output and delete it.

if (isset($_SESSION["flash"]))
{
    vprintf("<p class='flash %s'>%s</p>", $_SESSION["flash"]);
    unset($_SESSION["flash"]);
}

Note: The example assumes you are using PHP sessions already. If not, you must start the session first.

lxg
  • 12,375
  • 12
  • 51
  • 73
2

I would advise you use a session to display your message. The issue with $_GET is that since you rely on the URL, anyone can constantly manipulate the message being displayed.

Before calling header(), save the success or failed message to a session variable. For example

$_SESSION['success'] = 'Data Saved to Database';

On the index page, check for the session key, echo it and then remove it from the session array.

if(!empty($_SESSION['success'])){
  echo $_SESSION['success'];
 unset($_SESSION['success']);//so you do not have to display it over and over again
}
Rotimi
  • 4,783
  • 4
  • 18
  • 27
0

Why not use a JavaScript redirection with a delay ?

<?php echo dangerMessage("Heyho, I am a message!"); ?>
<script type="text/javascript">
    $(document).ready(function() {
        var target = 'index.php';
        setTimeout(function() {
            location.replace(target);
        }, 1500);
    });
</script>

The above code will show your alert message, then redirect the page 1.5 seconds after it's effectively loaded. It uses jQuery, but is easily adaptable for native JS.

roberto06
  • 3,844
  • 1
  • 18
  • 29
0

I like this solution with sessionStorage. This is fully client side, but will work fine when a modern browser is used.

When your text for the next page is ready:

<script>
sessionStorage.setItem("my_report", <?php echo json_encode( $whatever_you_want_to_say ); ?> );
</script>

Then redirect. At the top of the script you are redirecting to, obtain the message and do something with it, for example:

<script>
var msg = sessionStorage.getItem("my_report");
if( msg ){
    document.write( msg );
    sessionStorage.removeItem("my_report");
}
</script>

PHP header() will not work in this scenario. The header() function must be called before any actual output is sent to the browser. But since the magic happens at the client side, you need to send output to the browser. Therefore, you will need a JavaScript redirect, for example

window.location = "?<?php echo $_SERVER['QUERY_STRING']; ?>";
-2

One way is to use the power of $_GET, first modify your header() to something like this:

header('refresh: 1.5 ; url = index.php?success'); //or whatever you want to put after ?
exit;

Then in index.php, put something like this:

if(isset($_GET['success'])){
    //display your message here
}
if(isset($_GET['error'])){
    //display your message here
}

This will check the URL for either success or error, then runs the code block inside if detected

Carl Binalla
  • 5,393
  • 5
  • 27
  • 46
  • @Swellar: This is an inferior solution in several ways. For example, think of what happens if a search engine indexes the page … every new visitor will see a random error or success message. – lxg Feb 07 '18 at 08:39
  • @lxg Got your point, and thank you for the info. Although I think I will not delete this answer unless this gathered too many down-votes or OP selects an answer. This just adds another option to the OP's problem. – Carl Binalla Feb 07 '18 at 08:42
  • dont search engines ignore query strings? – Brian Patterson Feb 07 '18 at 08:47
  • @BrianPatterson: Definitely not. The query string is part of the URL and it is expected that it influences what is seen on the page. A search engine removing query strings would be stupid. – lxg Feb 07 '18 at 09:05
  • i would assume in this case op would not be indexing destination page. could use echo ''; – Brian Patterson Feb 07 '18 at 09:29