1

new to PHP and trying to get this simple countdown timer to work. Basically, I just need to count down how many minutes are left of every hour in the day and make the timer restart every hour on the hour.

I've been trying to go off of some examples here but can't seem to get anything to work. Here's what I have...i'm sure i'm way off at this point:

<?php

$now = time();
$future_hour = time('next hour')
$interval = $future_hour->diff($now);
echo "There are". $interval ."minutes until the next update.";

?>
pr0digy
  • 72
  • 1
  • 3
  • 12
  • Time returns an integer timestamp in seconds and takes no arguments. `$seconds_until_next_hour = 3600 - time() % 3600;` – Sammitch Dec 06 '18 at 19:00
  • 1
    Why not 60 minus current minutes? `print(60-(date("i",time()))." min left");` – ivanivan Dec 06 '18 at 19:10
  • ivanivan - that works, but how do i get this to count down on the page? seems like i have to refresh the page to see it actually countdown – pr0digy Dec 06 '18 at 19:16

1 Answers1

1

This is not a very good idea to use PHP instead of JS for this type of task. Anyway we can implement countdown timer via PHP, but if we want to show it on the web page we also need to use AJAX request to update our data.

index.html:

<html>
<head>
    <script
            src="https://code.jquery.com/jquery-3.3.1.js"
            integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
            crossorigin="anonymous"></script>
</head>
<body>
<h1 id="countdown"></h1>
<script>
    jQuery(document).ready(function() {
        time=setInterval(function(){
            jQuery(function () {
                jQuery.ajax({
                    url: "countdown.php",
                    method: 'post',
                    dataType: 'json',
                    data: {},
                    complete: function (data) {
                        jQuery("#countdown").html(data.responseText);
                    }
                });

            });
        },1000);
    });
</script>
</body>
</html>

countdown.php:

<?php

echo date("i:s",3600-(date("s",time())))." left";
exit();  

If you need only minutes left (without seconds), your code should look like this:

echo (60-(date("i",time()))." min left");

See also:
https://www.w3schools.com/howto/howto_js_countdown.asp
The simplest possible JavaScript countdown timer?