Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

header location delay

Tags:

php

I have the following php code which I want to add a delay too:

<?php
    echo "Message has been sent.";
    header("Location: page2.php", true, 303);
    exit;
?>

The above code happens too fast so I can't see the message:

I have tried:

<?php
    sleep(5);
    echo "Message has been sent.";
    header("Location: page2.php", true, 303);
    exit;
?>

This doesn't display the message either, but it does sleep for 5 seconds, which is just a waste of time.

How do I get it to display a message for 5 second before redirecting?

like image 941
oshirowanen Avatar asked Jul 02 '12 18:07

oshirowanen


4 Answers

You cannot do this with a HTTP location redirect, as this redirect will happen as soon as the browser gets the header. Instead, use a refresh redirect in the header:

header( "Refresh:5; url=http://www.example.com/page2.php", true, 303);

This should work on modern browsers, however it is not standardized, so to get the equivalent functionality would be do use a meta refresh redirect (meaning you'd have to output a full HTML too):

<meta http-equiv="refresh" content="5;url=http://www.example.com/page2.php"> 

From the Wikipedia page:

Used in redirection, or when a new resource has been created. This refresh redirects after X seconds. This is a proprietary, non-standard header extension introduced by Netscape and supported by most web browsers.

like image 109
nickb Avatar answered Oct 13 '22 01:10

nickb


Do the redirect using client-side scripting:

<script>
window.setTimeout(function() {
    window.location = 'page2.php';
  }, 5000);
</script>
<p>Message has been sent.</p>
like image 31
Emil Vikström Avatar answered Oct 13 '22 01:10

Emil Vikström


You have to modify your code like this:

<?php

    echo "Message has been sent.";
    sleep(5);
    header("Location: page2.php", true, 303);
    exit;
?>
like image 3
Ali Avatar answered Oct 13 '22 02:10

Ali


You won't be able to see the message if you're using a header(Location) redirect. In fact, that redirect shouldn't work at all since output starts before the headers are sent. Instead, you should echo a meta tag refresh with a delay, like this echo '<meta http-equiv="refresh" content="5;URL=\'http://example.com/\'">';

which will have a delay of five seconds. Alternatively, (and more properly) you could output a JS redirect, as the meta refresh tag is deprecated.

like image 2
Lusitanian Avatar answered Oct 13 '22 02:10

Lusitanian