Question

I want to dynamically display time using PHP in the web browser.

My code is:

<?php
date_default_timezone_set('UTC');
for($j=0;$j<5;$j++)
{
echo nl2br("\n");
sleep(1);
echo date(" H:i:s", time());
}
?>

The web page displays a list of 5 time stamps together instead of printing it every second. I don't know where I went wrong.

Was it helpful?

Solution

PHP is server side code. Once it has been sent to the client, it can no longer update the page. To do what you want you need JavaScript.

A quick google brought up a number of websites that can help you. This one looks fairly simple to implement.

OTHER TIPS

Using PHP to output the time will only show the time when the page was initially rendered. You cannot use only PHP to dynamically show what time it is. If you want to reach your end result, you will need to use JavaScript.

The caveat with using JavaScript's Date() object is that it will show the client's time based on the settings of their computer or device. If your goal is to use server time and allow it to tick, you would need to pass the current time to the Date() and then manipulate that data every second.

You could essentially do something like this:

Working example on CodePen: http://codepen.io/anon/pen/IAKht

<?php
date_default_timezone_set('UTC');
?>
<html>
<head>
<script>
var d = new Date(<?php echo time() * 1000 ?>);

function updateClock() {
  // Increment the date
  d.setTime(d.getTime() + 1000);

  // Translate time to pieces
  var currentHours = d.getHours();
  var currentMinutes = d.getMinutes();
  var currentSeconds = d.getSeconds();

  // Add the beginning zero to minutes and seconds if needed
  currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes;
  currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds;

  // Determine the meridian
  var meridian = (currentHours < 12) ? "am" : "pm";

  // Convert the hours out of 24-hour time
  currentHours = (currentHours > 12) ? currentHours - 12 : currentHours;
  currentHours = (currentHours == 0) ? 12 : currentHours;

  // Generate the display string
  var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + meridian;

  // Update the time
  document.getElementById("clock").firstChild.nodeValue = currentTimeString;
}

window.onload = function() {
  updateClock();
  setInterval('updateClock()', 1000);
}
</script>
</head>
<body>
  <div id="clock">&nbsp;</div>
</body>
</html>

I think php to javascript is not such a good idea, ... you won't make every second a server call. Better is a javascript client-side solution.

php is server side scripting language. that means it returns whole page generated as an HTML page. you can't print or echo values using loops. so the loop will display all values rather than displaying one by one.

for that you have to display time at regular interval. there are two way to do that client-side and server-side which is as below,

Server-side Get Time method

<html>
<body>

    <div id="timeNow" >
    </div>

    <script>
        var d = new Date(<?php date_default_timezone_set('UTC'); echo strtotime('now')*1000 ?>);
        (function foo(){
            d.setTime(d.getTime()+1000);
            var clientTime = d.getHours() + ":"  + d.getMinutes() + ":" + d.getSeconds() + " " + (d.getHours() >= 12 ? 'pm' : 'am');
            //alert(clientTime);
            document.getElementById("timeNow").innerHTML = clientTime;
            setTimeout(foo, 1000); // refresh time every 1 second
        })();
    </script>

</body>
</html>

Client-side Get Time method :

<html>
<body>

    <div id="timeNow" >
    </div>

    <script>
        (function foo(){
            var d = new Date();
            var hours = d.getHours()*12;
            var clientTime = (hours ? hours : 12) + ":"  + d.getMinutes() + ":" + d.getSeconds() + " " + (hours >= 12 ? 'pm' : 'am');
            //alert(clientTime);
            document.getElementById("timeNow").innerHTML = clientTime;
            setTimeout(foo, 1000); // refresh time every 1 second
        })();
    </script>

</body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top