php server time countdown javascript


Well basically I have a 30 minutes countdown in Javascript. Currently Javascript
get's the time from user's computer (client side). So if the user's computer clock
is incorrect then the countdown will show wrong time.

What I want is that javascript to get time from SERVER using php. So that javascript
will be based on server's time and not client side user's computer time.

the php also should have some kind of expiry date om when the countdown fully stops

I appreciate any help, thanks!

Below is the script


  var interval, m=30, s=0;
  function countdown() {
    if(s==0) {if(m==0) {clearInterval(interval); return;} m-=1; s=60;}
    document.getElementById("time").innerHTML = m + ":" + (s<10?"0":"") + s;
<body onload="interval=setInterval('countdown();',1000);">
<div id="time">30:00</div>
Who is Participating?
TheClickMasterConnect With a Mentor Commented:
// Configuration ----------------------------
// Change this to change the countdown time
$Time["hour"] = 19;
$Time["minute"] = 23;
$Time["second"] = 10;

//get the current date/time
$current_time = getdate();

// calculate the remaining minutes and seconds
$min = ($Time["hour"] - $current_time["hours"]) * 60;
$min += ($Time["minute"] - $current_time["minutes"]);
$sec = ($Time["second"] - $current_time["seconds"]);

// make sure we get something valid even if we already passed the time limit

// if the number of seconds is below 0
if ($sec < 0)
      // we remove 1 minute
      $min --;
      // if there really was 1 minute, we add 60 seconds
      if ($min >= 0)      $sec += 60;
// if the number of minutes is below 0 we adjust it to 0
if ($min < 0) $min = 0;

// display the page with the javascript
// we use $min and $ sec to initialize the variables and the display
print "
  var interval, m=".$min.", s=".$sec.";
  function countdown() {
    if(s==0) {if(m==0) {clearInterval(interval); return;} m-=1; s=60;}
    document.getElementById(\"time\").innerHTML = m + \":\" + (s<10?\"0\":\"\") + s;
<body onload=\"interval=setInterval('countdown();',1000);\">
<div id=\"time\">".$min.":".$sec."</div>
you will have to use php to generate the javascript code
then use getdate() function to pull out the time from the server.

$now = getdate();
$hours = $now['hours'];
$minutes = $now['minutes'];
$seconds = $now['seconds'];

print "<script language=\"JavaScript\">";
print "var interval,m=$minutes,s=$seconds;
print "</script>";

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.