Let’s create a Countdown Timer in PHP

The following PHP snippet can be used to display a countdown timer on a web page.

Start by creating a new PHP page in your code editor. In the beginning of the code we need to start a PHP session by calling the session_start() function:

<?php
session_start();

Next, we’ll set the default time zone for our region. I am in Sri Lanka so I can set it to Asia/Colombo:

date_default_timezone_set('Asia/Colombo');

Now add the below code block:

if(!isset($_SESSION['expire'])){
      $_SESSION['expire'] = time()+3600;
}

In the above piece of code, we were checking to see if the expire variable was set in the session. If it wasn’t, we set the expire variable’s value to a timestamp of an hour from now. time() gives the current timestamp and we add 3600 seconds to make it an hour ahead than what the current time is. (1 hour == 3600 seconds)

Now we need to calculate the difference between the expiration time we’ve set and the current time. This should give us the remaining time (in seconds) till we meet the expiration time.

$time_remaining = $_SESSION['expire'] - time();

Finally we can add below statement to display the remaining time:

echo round(abs($time_remaining) / 60, 2) . ' minutes to go ...';

In that last line we were doing several things. We have taken the absolute value of the $time_remaining by running it through abs() function. Then we have divided it by 60. That is because $time_remaining has number of seconds till the expiration, so we have to divide it by 60 to get the result in minutes (60 seconds == 1 minute). Finally we run the resulting value through the round() function with precision of two digits. This way, the resulting number will clearly tell us how many minutes as well as seconds remaining until the expiration. To polish things up, we have also appended the text ‘ minutes to go…’ to the end result.

Your final script should look similar to following:

<?php
session_start();
 
date_default_timezone_set('Asia/Colombo');
 
if(!isset($_SESSION['expire']))
{
    $_SESSION['expire'] = time()+3600;
}
 
$time_remaining = $_SESSION['expire'] - time(); 
 
echo round(abs($time_remaining) / 60, 2) . ' minutes to go ...';

When you save and run this script in your browser, you should see it starts with 60 minutes to go. Then on every time you refresh the page, it should indicate that the time is counting down from initial 60 minutes.

Bye for now!!! 👋👋👋

Was this helpful?
+1
0
+1
1
+1
0
+1
0
+1
0
+1
0
+1
2