April 2, 2012

PHP, counting time script

Question by Jake

Is there a way to make a countdown script with PHP?

4shared.com or megaupload.com use similar script, and it starts to count from 20 seconds to 0 second.

I can clearly see how many seconds left on the web page until I can click download page.

Is this jquery?

Answer by landons

This is with a simple javascript timer. It’s just as easy with native javascript as it is with jQuery (or any other library):

<script type="text/javascript">
var seconds_left = 20;
var interval = setInterval(function() {
    document.getElementById('timer_div').innerHTML = --seconds_left;
    if (seconds_left == 0)
    {
        clearInterval(interval);
        alert('do something here!');
    }
}, 1000);
</script>

Answer by Starx

You need to mix up PHP & Javascript for this

First PHP

Send headers, so that page will navigate to the download page .

header( "refresh:30;url=download.php" );
echo 'The download will begin in 30 secs. If not, click <a href="download.php">here</a>.';

Then Javascript

This handles the part where we show time to the user, so that he know.

var count=30; //30 seconds
var counter = setInterval(timer(),1000); //1000 will  run it every 1 second
function timer()
{
  count=count-1;
  if (count <= 0)
  {
     clearInterval(counter);
     return;
  }

  document.getElementById("placetoshowtime").innerHTML = count; //display the time to user
}

Small demo of JS Part.

When, the java script finishes ticking, the PHP will already have redirected to download page. So it creates the illusion you are after.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!