PHP Countdown Timer

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

First we need to start a PHP session by calling the session_start() function:

	session_start()

Then set the default time zone for your region. I am in Sri Lanka so I set it to Asia/Colombo

	date_default_timezone_set('Asia/Colombo');

Now add below code block:

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

In that part we were checking to see if ‘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 time stamp and we add 3600 seconds to make it an hour ahead than the current time. (1 hour == 3600 seconds)

Now we need to calculate the difference between the expiration time we’ve set above and the current time. This gives us the remaining time since we meet the expiration time.

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

Finally add below statement to display the remaining time:

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

In that last line we are 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 number of seconds 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. at last we have appended the text ‘ minutes to go…’ to the end result.

Your final script should look as follows:

	<?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 ...';

Now save and run this script in your browser. you should see it starts with 60 minutes and every time you refresh its counting down from 60.

Comments

This post currently has 4 responses

Leave a Reply

Your email address will not be published. Required fields are marked *

Sidebar



Do NOT follow this link or you will be banned from the site!