PHP Timer Countdown.

This is a small tutorial on how to implement a server-side countdown with PHP.

Although client-side languages such as JavaScript are typically used for countdown timers, there can be certain scenarios where a timer needs to be enforced on the server.

The problem with trying to implement a server side countdown is that HTTP is stateless. i.e. By default, your web server will treat each request in an individual manner. It won’t remember who you are and it certainly won’t remember what stage your countdown timer was at when you previously loaded a web page.

Session Timer.

A way around this is to use sessions in PHP. Let’s have a look at a timer example:

<?php

//You must call the function session_start() before
//you attempt to work with sessions in PHP!
session_start();

//Check to see if our timer session variable
//has been set. If it hasn't been set, "initialize it".
if(!isset($_SESSION['timer'])){
    //Set the current timestamp.
    $_SESSION['timer'] = time();
}

//Get the current timestamp.
$now = time();

//Calculate how many seconds have passed.
$timeSince = $now - $_SESSION['timer'];

//Print out the result.
echo "$timeSince seconds have passed.";

The code snippet above will tell you how much time has passed since you first loaded the web page. If you continue to refresh the page, you will see that the $timeSince variable continues to increase as time goes on.

But what if we want to implement a countdown timer that will eventually reach zero?

Session Countdown.

In this code snippet, we extend the logic that we used in the first example.

<?php

//You must call the function session_start() before
//you attempt to work with sessions in PHP!
session_start();

//Check to see if our countdown session
//variable has been initialized.
if(!isset($_SESSION['countdown'])){
    //Set the countdown to 120 seconds.
    $_SESSION['countdown'] = 120;
    //Store the timestamp of when the countdown began.
    $_SESSION['time_started'] = time();
}

//Get the current timestamp.
$now = time();

//Calculate how many seconds have passed since
//the countdown began.
$timeSince = $now - $_SESSION['time_started'];

//How many seconds are remaining?
$remainingSeconds = abs($_SESSION['countdown'] - $timeSince);

//Print out the countdown.
echo "There are $remainingSeconds seconds remaining.";

//Check if the countdown has finished.
if($remainingSeconds < 1){
   //Finished! Do something.
}

Steps:

  1. We start our session.
  2. We check to see if our PHP countdown has started. If not, we start it by initializing our session variables.
  3. We work out how much time has passed since our countdown timer was first initialized.
  4. We print out the result.
  5. Finally, we check to see if the countdown has finished (if $remainingSeconds has reached 0).

As you can see, it’s actually not that difficult!