Redirect 10 second Countdown

  • Added:
  • |
  • In: Wordpress

I have a page which redirects a user after 10 seconds with the following code.

<META HTTP-EQUIV="refresh" CONTENT="10;URL=login.php">

I then have this code which is echo'd in PHP, and would like the "10" (seconds) to countdown dynamically as 10, 9, 8, 7... so the user can see the seconds left until the page redirects.

echo "We cant find you on the system. <br/> Please return to the <b><a href='login.php'>Login</a></b> page and ensure that <br/>you have entered your details correctly. 
<b>Warning</b>: You willl be redirected  back to the Login Page <br> in <b>10 Seconds</b>";

I was wondering if there was a way that this can be done in PHP, if not what would be the best way to achieve the same?

This Question Has 4 Answeres | Orginal Question | user1662306

The following will redirect the user right away to login.php

header('Location: login.php'); // redirects the user instantaneously.

You can use the following to delay the redirection by X seconds but there is no graphical countdown (thanks to user1111929):

header('refresh: 10; url=login.php'); // redirect the user after 10 seconds
#exit; // note that exit is not required, HTML can be displayed.

If you want a graphical countdown, here's a sample code in JavaScript:

<p>You will be redirected in <span id="counter">10</span> second(s).</p>
<script type="text/javascript">
function countdown() {
    var i = document.getElementById('counter');
    if (parseInt(i.innerHTML)<=0) {
        location.href = 'login.php';
    i.innerHTML = parseInt(i.innerHTML)-1;
setInterval(function(){ countdown(); },1000);

header("Refresh: 2; url=$your_url");

Remember not to put any html content before the header.

You cannot do this with pure PHP - but javascript is your friend here.

Change your HTML to put the number of seconds in a span:

<b><span id="count">10</span> Seconds</b>

Then remove your meta tag and use this javascript:

var count = 10;
function decrement() {
    if(count == 0) {
        window.location = 'login.php';
    else {
        document.findElementById("count").innerHTML = "" + count;
        setTimeout("decrement", 1000);
setTimeout("decrement", 1000);

This will decrement the count on the page every second and then redirect to login.php when the counter reaches 0.

I would use javascript for this

var counter = 10;
setInterval(function() {
    if(counter < 0) {
        window.location = 'login.php';
    } else {
        document.getElementById("count").innerHTML = counter;
}, 1000);?


Meet with owner

Sajjad Hossain

Hey, I am Sajjad, working in web development sector since 2012. I love to do amazing things. Let's do a project together.
Connect Social With PHPAns