4

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.

4
  • 5
    You can't use PHP alone for dynamic content, since it is processed on the server and not on the client. You need to use javascript. Commented Jan 17, 2014 at 14:36
  • AJAX, jQuery, JavaScript are your only options really Commented Jan 17, 2014 at 14:36
  • 1
    Instead you can use Javascript Date() object. Commented Jan 17, 2014 at 14:38
  • @Swamy if you have your answer please mark one as correct to close the question. Commented Jan 23, 2014 at 9:10

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

-1

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.

1 Comment

This shoulb be a comment ! Please read stackoverflow.com/help/how-to-answer
-1

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>

3 Comments

This will make an HTTP request every second. This is horrible-practice. Do not do this.
yaa but if any one want to get the server time than there is no any other option except this.
Your second method uses client time, not server time. If the OP is looking for client-side time, that may work. However, if they are looking for server-based time, neither of your solutions are acceptable. There are other options, such as my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.