How to make a countdown using PHP

This tutorial will show you how to implement a server-side countdown with PHP.

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

The problem with creating a server-side countdown is that HTTP is stateless. By default, your web server will treat each request individually. As a result, you will need to use sessions.

Session timer.

Take a look at the following example:

//You must call session_start() first
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 above calculates how much time has passed since the user first loaded the page. If you refresh your browser a few times, you will see that the $timeSince variable increases.

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

PHP session countdown.

In the next example, we will extend the logic that we used above.

//Start the session
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 the seconds remaining.
echo "There are $remainingSeconds seconds remaining.";

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

In the code above:

  1. We start our session.
  2. We check to see if our PHP countdown has already started. If not, we initialize our session variables.
  3. After that, we calculate how much time has passed since our timer was first initialized.
  4. We print the result.
  5. Finally, we check to see if the countdown has finished.