How to make a countdown using PHP

If your need your counter to be displayed only on page refresh and be static once the page is loaded, then PHP will be fine.

If you need the countdown to get refreshed when the page is displayed, you'll need to use JavaScript.

Personally I would go for something already implemented, like that small script.


For Static Countdown :

<?php

//A: RECORDS TODAY'S Date And Time
$today = time();

//B: RECORDS Date And Time OF YOUR EVENT
$event = mktime(0,0,0,12,25,2006);

//C: COMPUTES THE DAYS UNTIL THE EVENT.
$countdown = round(($event - $today)/86400);

//D: DISPLAYS COUNTDOWN UNTIL EVENT
echo "$countdown days until Christmas";

?>

Following is the code snippet I have copied from the W3Schools website, while added my PHP code to get the "countdown to" timestamp and the "now" timestamp.

You will see I have commented out the original JavaScript code and replaced it with PHP code in two places, so it's clear to tell what's the difference between two options.

Basically when you think the "server time" is more reliable in your case, you can adopt the PHP approach.

<!DOCTYPE HTML>
<html>

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
    p {
        text-align: center;
        font-size: 60px;
        margin-top: 0px;
    }
    </style>
</head>

<body>
    <p id="demo"></p>
    <script>
    // Set the date we're counting down to
    // 1. JavaScript
    // var countDownDate = new Date("Sep 5, 2018 15:37:25").getTime();
    // 2. PHP
    var countDownDate = <?php echo strtotime('Sep 5, 2018 15:37:25') ?> * 1000;
    var now = <?php echo time() ?> * 1000;

    // Update the count down every 1 second
    var x = setInterval(function() {

        // Get todays date and time
        // 1. JavaScript
        // var now = new Date().getTime();
        // 2. PHP
        now = now + 1000;

        // Find the distance between now an the count down date
        var distance = countDownDate - now;

        // Time calculations for days, hours, minutes and seconds
        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

        // Output the result in an element with id="demo"
        document.getElementById("demo").innerHTML = days + "d " + hours + "h " +
            minutes + "m " + seconds + "s ";

        // If the count down is over, write some text 
        if (distance < 0) {
            clearInterval(x);
            document.getElementById("demo").innerHTML = "EXPIRED";
        }
    }, 1000);
    </script>
</body>

</html>

Tags:

Php

Countdown