This tutorial will walk you through how to create a PHP Countdown Timer that can be used as a landing page for launching a site. This is a very common practice and can be a great way to market and hype up the launch of you next website project. By simply retrieving the date from a server and performing a couple lines of math, you can easily create a dynamic countdown. Let’s begin.
Read More: INSERT ELEMENTS WITHIN A PHP LOOP
Setting up the Project
To begin, we must first create a .php file to place all of our code in. To keep things simple for this demonstration, we will be containing everything within one php tag and echo the output in the second tag. The idea to make this demonstration work is simple, “specify a date, retrieve the current time, subtract the current time from the target date”. Once we get this number, we will have to do some more math in order for the user to see it in the typical x days and 12:00 am setting.
<title>PHP Countdown Timer</title>
font-family:Arial, Helvetica, sans-serif;
$date = strtotime(“December 3, 2014 2:00 PM”);
$remaining = $date – time();
$days_remaining = floor($remaining / 86400);
$hours_remaining = floor(($remaining % 86400) / 3600);
<h1>There are <span class=“green”> <?php echo $days_remaining?></span> days and <span class=“green”> <?php echo $hours_remaining?></span> hours left</h1>
Let’s look at the first PHP section. We have four variables, each one containing a function that will let us store the result to use in the next function. Our first line uses the strtotime function which will convert our target date into a Unix time stamp giving us the number 1417644000 (which is the how many seconds till December 3rd). We take that number and subtract today’s timestamp to give the remaining time until December 3rd. To get the remaining days we have have php do the math of $remaining and divide it by 86400 (amount of seconds in a day). To get the hours, we take that number and divide it by 3600. Thus giving us the results we need.
We can now take those variables and place them inline with our heading statement. At this point you can add styling to your statement and setup the site the way you want.
Wrapping It Up
This was just an example of how to pull dates from a server and perform a dynamic function to display a countdown timer. By understanding the results given and knowing how to change the output, we were able to better the user experience and make our site more engaging. Practice this technique and try to output the day of the week for more PHP fun.