I want to display the echo for 5 seconds and redirect the page to login.html but when the page loads it takes 5 seconds instead of loading the page and waiting 5 sec then redirect.
<?php
session_start();
if (isset($_SESSION['name'])) {
echo $_SESSION['name'];
} else {
echo "Login To Order";
sleep(5);
echo "<script type=\"text/javascript\">
window.location.href = \"login.html\";
</script>";
}
?>
EDIT: ok this seems to delay it for 5 seconds but the code execution still continues further but I want it to stop =>echo for 5 seconds =>redirect to the other page.
echo "Login To Order";
echo "<script type=\"text/javascript\">
window.setTimeout(function() {
window.location.href=\"login.html\";
}, 5000);
</script>";
echo "this should not be displayed";
echo "this should not be displayed"; my point here is that I have others codes below that I don't want to be executed in the else case.
PHP pre-processes the page on the server, then sends the page to the client browser - sleeping on the server will rarely equate to a delay on the client
Put the delay on the client side using setTimeout
<?php
session_start();
if (isset($_SESSION['name'])){
echo $_SESSION['name'];
} else {
?>
Login To Order
<script>
setTimeout(function() {
window.location.href="login.html";
}, 5000);
</script>
<?php
exit(0);
}
?>
note how you can switch PHP preprocessing off ?>
to make the script easier to write, then switch PHP back on <?php
or even simpler, use a HTTP header to do the work for you
<?php
session_start();
if (isset($_SESSION['name'])){
echo $_SESSION['name'];
} else {
header("refresh:5; url=login.html");
?>
Login To Order
<?php
exit(0);
}
?>
sleep()
is processed by the server, before the DOM is rendered.
To redirect to another page after 5 seconds, you could always use the refresh
parameter of PHP's header()
:
header("refresh:5; url=login.html");
However, considering you also want to display output before the user gets redirected, you probably will want to use a setTimeout()
in the JavaScript:
window.setTimeout(function() {
window.location.href=\"login.html\";
}, 5000);
Hope this helps! :)
Instead of using PHP use Javascript to do what you want.
Here is a sample
<?php
session_start();
if (isset($_SESSION['name'])) {
echo $_SESSION['name'];
} else {
echo "Login To Order";
echo '<script>setTimeout(function(){ window.location.replace("http://stackoverflow.com"); }, 5000);</script>';
return;
/*other codes*/
}
?>