PHP Countdown Timer - php

Is it possible to create a timer using PHP so that after 60 seconds it does something. So it actually shows you a countdown from 60 to 0. I would refresh the div so it actually looks like it's counting down. I don't mind using JavaScript but I want to run the timer only when the $_GET variable is = to something.
For either option, can anyone help?
For now, I'm using this code I got from EpicSoftworks on Youtube but the problem with this code is that you have to specify the timestamp you want to use.
$future = -2211753540;
$current = time();
$difference = $future - $current;
$minutes = floor($difference/60);
$r_seconds = floor($difference - ($minutes = 60) );
echo '<h2>' . $minutes . ' - ' . $r_seconds . '</h4>';

use PHP to get the variable from the URL and then use javascript for the rest. Create a function that will run a loop 60 times. Inside that loop create a setTimeOut that will do something with a 1000 (1 second) timeout.

Related

PHP Session Timer Works Initially but Gone Wrong

So I have a php session timer that works but somehow gets bugged out after awhile... this is the code and the console log I got. I'm looking for a fix to this problem, or possibly a different set of code to achieve the same timer effect (as I'm not sure if using session is the best method for a timer)
session_start();
function timer($time) {
//Set the countdown to 120 seconds.
$_SESSION['countdown'] = $time*60;
//Store the timestamp of when the countdown began.
$_SESSION['time_started'] = time();
$now = time();
$timeSince = $now - $_SESSION['time_started'];
$remainingSeconds = abs($_SESSION['countdown'] - $timeSince);
$counter = 0;
$minutes = $remainingSeconds/60;
echo "$minutes minutes countdown starts.".PHP_EOL;
while($remainingSeconds >= 1) {
$now = time();
$timeSince = $now - $_SESSION['time_started'];
if (($timeSince-$counter) >= 60) {
$remainingSeconds = abs($_SESSION['countdown'] - $timeSince);
$counter = $timeSince;
$minutes = $remainingSeconds/60;
echo "$minutes minutes has passed.".PHP_EOL;
}
}
if($remainingSeconds < 1){
session_abort();
return true;
}
}
if($this->timer(30)) {
// do whatever
echo "$time has passed";
}
Here's what happens in the console:
30 minutes countdown starts.
29 minutes has passed.
.... (continue as per pattern)
16 minutes has passed.
15 minutes has passed. (problem occurs here)
8.7166666666667 minutes has passed.
7.7166666666667 minutes has passed.
6.7166666666667 minutes has passed.
.... (continue as per pattern)
0.71666666666667 minutes has passed.
0.28333333333333 minutes has passed.
1.2833333333333 minutes has passed.
2.2833333333333 minutes has passed.
.... (continue as per pattern all the way)
Extra notes: The session timer doesn't always recur this same pattern, there have been times when it ran through the entire 30minutes and managed to echo "$time has passed"; while the bug only occured later on
I haven't run your, but just from reading it I think there are a few things very wrong with it.
Sessions. You're not using them right.
Session values should only be set once, meaning before you do $_SESSION['countdown'] = $time*60; and $_SESSION['time_started'] = time();, you should check if they already exist or not, and only assign if nonexistent. Your current code resets the clock every time the page is refreshed, which defeats the purpose of sessions.
abs. I think you're not using them right either.
You shouldn't abs the remaining seconds all the time. $remainingSeconds = abs($_SESSION['countdown'] - $timeSince); should be allowed to go into negative. Negative remaining seconds mean your timeout has expired / you've missed it! Calling abs means you're effectively letting it go forever if you by any chance miss the exact time of your event. This is the answer to your main problem. Fix this and your counter will stop going to zero and back up again.
You're relying on your code correctly checking every single second. But it doesn't.
The nasty decimals you're getting happen when for some reason your code gets delayed and doesn't correctly check the 60th second, which means your division by 60 is not perfectly round and you get 8.7166666 minutes.
If you start by removing the abs calls and generally try to simplify your code a bit, I believe you'll quickly get it to work as intended.
// Edit 1
This is a very naive, but simplified approach to your problem. I left two different outputs in there for you to pick one.
function timer($time) {
echo "$time minutes countdown starts." . PHP_EOL;
// Save the date in future when the timer should stop
$endTime = time() + $time * 60;
// Keeps track of last full minute to simplify logs
$lastFullMinute = $time;
while(true) {
$timeRemaining = $endTime - time();
if ($timeRemaining <= 0) {
// Time remaining is less than zero, which means we've gone beyond the end date.
// End the loop
return;
}
// Round up!
$minutesRemaining = ceil($timeRemaining / 60);
if ($minutesRemaining != $lastFullMinute) {
// Current "minute" is different than the previous one, so display a nice message
// If you want to show how many minutes are remainig, use this:
echo "$minutesRemaining minutes remaining." . PHP_EOL;
// If you want to show how many minutes have passed, you have to take mintutesRemaining away from the original time
$minutesPassed = $time - $minutesRemaining;
echo "$minutesPassed minutes passed." . PHP_EOL;
$lastFullMinute = $minutesRemaining;
}
}
}
The main way for you to improve it further would be to use the sleep function http://php.net/manual/en/function.sleep.php. Currently the while loop will hog all the CPU by constantly checking if the timer happened, so you should sleep for a few seconds inside.
What do you think of this solution? referenced from above
function timer($time) {
echo "$time minutes countdown starts." . PHP_EOL;
// Save the date in future when the timer should stop
$endTime = time() + $time*60;
while(true) {
sleep(20);
$secondsRemaining = $endTime - time();
if ($secondsRemaining <= 0) {
echo 'Finished';
return true;
}
}
}

PHP/SQL Variable manipulation

I have the following variables:
$days_a = $array_total['days']; // This one display days
$hours_a = $array_total['hours']; // This one display hours
$minutes_a = $array_total['minutes']; // This one display minutes
$seconds_a = $array_total['seconds']; // This one display seconds
These variables give me the current session time, here all works.
Now the problem...
I have then these variables:
$days_f = $fetch_s['days'];
$hours_f = $fetch_s['hours'];
$minutes_f = $fetch_s['minutes'];
$seconds_f = $fetch_s['seconds'];
These display the time that the user entered in the website previously, they took the values from the database... I did this for add the current session variable values to the values in the MySQL Db:
$days_2 = $days_a + $days_f;
$hours_2 = $hours_a + $hours_f;
$minutes_2 = $minutes_a + $minutes_f;
$seconds_2 = $seconds_a + $seconds_f;
But I need that each 60 seconds it add 1 to $minutes_2 , each 60 minutes it add 1 to $hours_2 and each 24 hours it add 1 to $days_2
For example if I have 118 seconds I need that it adds 1 to $minutes_2 and set the variable $seconds_2 to 58 etc...
How can this be done?
I tried something like that:
$seconds = $seconds_2 % 60;
$minutes_3 = $seconds_2 / 60;
$minutes = $minutes_3 % 60;
$hours_3 = $minutes / 60;
$hours = $hours_3 % 24;
$days = $hours / 24;
$days = (int)$days_int;
But this won't work... Someone know how do that in a similar or different way?
Could someone give me the code? Please
In my experience it is easier to do these calculations by converting to UNIX seconds for a given time, adding the seconds, the converting back. That way the system does all the day, hour, minute and seconds book-keeping for you. Use e.g. mktime to convert to UNIX seconds (you can use your existing time parameters), and date, strftime to convert back to day, hour, minutes, seconds.

countdown timer using php, can't make it work

i am making a php countdown timer that display only minutes and seconds.
here is my code:
$time = "10:00";
$time_min = substr($time, 0,2);
echo $time_sec = substr($time, 3) . "<br>";
$current = date("i:s");
$target = date("i:s" , mktime(0,$time_min,0,0,0,0));
echo $current-$target . "<br>";
echo $target;
the output should be the remaining time from the time the user opens the page.
Not knowing the details of your jQuery I am taking a shot at this.
I prefer working in seconds, so to get the $timeRemaining (you must know the initial time to do this) at any given instant in the 10 minute window, I would do this:
$targetTime = time() + 600; //you have to save this either in database or as variable somewhere
Then on subsequent opening of relevant php file the following code could be used if targetTime is saved in database
$sqlTime = mysqli_fetch_assoc(mysqli_query($cxn, "SELECT targetTime FROM timeTable WHERE id = '$myID'"));
$currentTime = time();
$timeRemaining = (($sqlTime['targetTime'] - $currentTime) / 60) . ":" . (($sqlTime['targetTime'] - $currentTime) % 60);

countdown php jquery post ajax

I'm designing a website where there is a little game going on. Each user that participates has 99 minutes to complete it otherwise we display a game over state. Here is what I managed to do so far using jQuery post.
I've been able to display the timer. In the PHP I've set the target time to 99*60 seconds but I cant set the starting time to 0 as I'll do the difference beteen those to values for the countdown.
Furthermore, as each user is able to quit the page I want to be able to store the time when they left. All I am able to do is store the countdown value, let's say 5845, in the DB when they log off. Though I tried updating the table with each call to the jQuery post, it just makes it worse.
Here is my jQuery:
function countdown() {
var i = (new Date().getTime() / 1000) + (99 * 60);
setTimeout(function () {
$.post(\'countdown.php\',{target:i},function(data){
$('#countdown').html(data);
});
countdown();
},1000);
}
countdown();
Here is the PHP:
if (!empty($resm['Countdown']) || $resm['Countdown'] >= 0) {
$target = (99 * 60);
$countdown = ($target - $current);
$_SESSION['currenttime'] = $countdown;
$hours = floor($countdown / 3600);
$min = floor($countdown / 60);
$r_min = floor(($countdown - ($hours * 3600)) / 60);
$sec = floor($countdown - ($min * 60));
if ($min == 0) {
echo $target.' '.$current.' '.$countdown;
echo '<br/>'.$min.' minutes '.$sec.' seconds left';
} else {
echo 'Time Over';
$sql = "UPDATE bs10000099 SET Upgradedlevel='2',Activated='2',Countdown='5940' WHERE MemberID='$memberid'";
mysql_query($sql);
}
}
I cant figure out how to set the starting time or how to prevent countdown() restart on refresh page.
I'm not sure what kind of security you want, but getting time from Javascript is not really secure since JS gets the time from the computer instead of the server.
With your example, I would be able to play the game, wait until there's 10 minute left, and just roll back time on my desktop and it will reset. Or roll back a year and have 100000 minutes left!
I suggest you use server time.
Here is what I would do:
When the test starts, get the UNIX time + 90 minutes. This will give you the final time.
PHP
if (!isset($_SESSION['end'])) {
$_SESSION['end'] = strtotime("+90 minutes");
}
$remaining = $_SESSION['end'] - time();
if ($remaining > 0) {
echo json_encode(array(
"remaining" => $remaining
));
} else {
// finished! write code here.
}
You can then do a simple $.getJSON() to get the remaining seconds and display it.
Since you kept the "end" time, even if the users leave, the timer will continue.

Calculate elapsed time in php

Hi All I'm trying to calculate elapsed time in php. The problem is not in php, it's with my mathematical skills. For instance:
Time In: 11:35:20 (hh:mm:ss), now say the current time is: 12:00:45 (hh:mm:ss) then the time difference in my formula gives the output: 1:-34:25. It should actually be: 25:25
$d1=getdate();
$hournew=$d1['hours'];
$minnew=$d1['minutes'];
$secnew=$d1['seconds'];
$hourin = $_SESSION['h'];
$secin = $_SESSION['s'];
$minin = $_SESSION['m'];
$h1=$hournew-$hourin;
$s1=$secnew-$secin;
$m1=$minnew-$minin;
if($s1<0) {
$s1+=60; }
if($s1>=(60-$secin)) {
$m1--; }
if($m1<0) {
$m1++; }
echo $h1 . ":" . $m1 . ":" . $s1;
Any help please?
EDIT
Sorry I probably had to add that the page refreshes every second to display the new elapsed time so I have to use my method above. My apologies for not explaining correctly.
This will give you the number of seconds between start and end.
<?php
// microtime(true) returns the unix timestamp plus milliseconds as a float
$starttime = microtime(true);
/* do stuff here */
$endtime = microtime(true);
$timediff = $endtime - $starttime;
?>
To display it clock-style afterwards, you'd do something like this:
<?php
// pass in the number of seconds elapsed to get hours:minutes:seconds returned
function secondsToTime($s)
{
$h = floor($s / 3600);
$s -= $h * 3600;
$m = floor($s / 60);
$s -= $m * 60;
return $h.':'.sprintf('%02d', $m).':'.sprintf('%02d', $s);
}
?>
If you don't want to display the numbers after the decimal, just add round($s); to the beginning of the secondsToTime() function.
Using PHP >= 5.3 you could use DateTime and its method DateTime::diff(), which returns a DateInterval object:
$first = new DateTime( '11:35:20' );
$second = new DateTime( '12:00:45' );
$diff = $first->diff( $second );
echo $diff->format( '%H:%I:%S' ); // -> 00:25:25
Keep track of your time using the 'time()' function.
You can later convert 'time()' to other formats.
$_SESSION['start_time'] = time();
$end_time = time();
$end_time - $_SESSION['start_time'] = 65 seconds (divide by 60 to get minutes)
And then you can compare that to another value later on.
Use microtime if you need millisecond detail.
You can implement the solutions shown, but I'm fond of using the phptimer class (or others, this wheel has been invented a few times). The advantage is that you can usually define the timer to be active or not, thereby permitting you to leave the timer calls in your code for later reference without re-keying all the time points.
For high resolution time, try using monotonic clock: hrtime
<?php
$time = -hrtime(true);
sleep(5);
$end = sprintf('%f', $time += hrtime(true));
?>
Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

Categories