How can I countdown for 7 hours from a variable time (I will get time from my table which is inserted with timestamp), after 7 hours from variable time I will update a table.
I need something like that
$time = 2013-05-18 02:00:00 // comes from database
$target = $time + 7hours // time from database +7hours will be 2013-05-18 09:00:00
$until = $target - $time
I need something like below code
if ($until > 0 ) {
echo "you need to wait for $until hours"
} else {
echo "time is ok"; // i will update a table
}
Convert time into string using strtotime($time)+25200 where 7 hour =60*60*7=25200 sec and then check and also add this file to your cron job.
So, considering that $database_time is the stored time, in your db, and $time_now is your computers time, this message below, just echoed out:
You Must wait 4 hours right, now
It could be done much better, but still calculates the hours from now, to db and tells you how much more, you must wait :)
<?php
$date = date_create();
$database_time = '2013-05-18 22:00:00';
$time_now = date_format($date, 'Y-m-d H:i:s');
$check = $database_time[11];
$check .= $database_time[12];
$check2 = $time_now[11];
$check2 .= $time_now[12];
$time_left = $check - $check2;
So, here is how you can manage your ourputs
if($time_left > 0) {
echo "You Must wait $time_left hours right, now";
}else{
echo "Time is OK";
}
Related
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;
}
}
}
Difference is a MySQL time. I am trying to check if the MySQL time returned is greater than 5 minutes. I have tried the code below but it doesn't seem to be working.
if (strtotime($myMySQLTimeValue) > strtotime("+5 minutes",)) {
// My code if MySQL time is greater than 5 minutes
}
Any ideas?
If you already have the time in the format 00:06:43 then you could use the following code
$diff_time = "00:06:43";
$diff_arr = split(":", $diff_time);
// Check mins and hours
if ( intval($diff_arr[1]) >= 5 || intval($diff_arr[0]) > 0) {
echo "Time more then 5 min";
} else {
echo "Time less then 5 min";
}
Assuming you retrieved mysql time by "SELECT NOW()", you can use below comparison:
$_5minuteslater = time() + 5 * 60;
if ($mysqlTime > $_5minuteslater) {
}
I need to have a validation that checks if the "last_update" is done before 3 hours or less.
I have this PHP code:
if($user['last_update'] < strtotime("3 hours")) {
$msg .= "You can only register every 3 hour.";
}
How could this be done?
If $user['last_update'] is in date format, then
if (time() - strtotime($user['last_update']) < 3 * 3600) {
//..
}
Try like this. Wrap your $user['last_update'] inside strtotime().
if(strtotime($user['last_update']) < strtotime("3 hours")) {
$msg .= "You can only register every 3 hour.";
}
You can use this to get the current time minus 3 hours:
$dateTime = new DateTime();
$dateTime->modify("-3 hours");
$time = $dateTime->format("H:m:s");
$date = $dateTime->format("Y-m-d");
You can then compare the date and time variables with your last update.
strtotime()
returns seconds.
If your date is stored as UNIX timestamp, then your code is correct.
If your date is stored as TIMESTAMP, following will be the code:
$three_hours = date('Y-m-d H:i:s', strtotime('3 hours'));
if ($user['last_update'] < $three_hours) {
$msg .= "You can only register every 3 hour.";
}
I got a voting script that allow people to vote for an item in the database every 24 hour and some more code to check if 24 hours have past or not using 'NOW()' and 'DATE_SUB( NOW(), 'INTERVAL 1 DAY'.
I'm currently trying to add the feature to display how much time is left before the user can vote again using the code below.
$time = explode(" ", $voteCheck[1]);
$year = explode("-", $time[0]);
$date = explode(":", $time[1]);
// Set it all to one long string
$time = $year[0].$year[1].$year[2].$date[0].$date[1].$date[2];
// Current time and date
$cTime = date("YmdHis");
// I get lost here
votcheck is an array from a sql string which just returns the first row as 0 or 1.
1 if the user already voted and 0 if the user can vote again.
The second row returns the date and time the user voted.
I just can't seem to figure out what to do to get the x amount of hours left before the user can vote again.
My main problem is that the length of the $time string sometime is 13 and sometime 14 characters long.
Ok here it is
$voted = new DateTime($time);
$daylater = date('Y-m-d H:i:s', strtotime('+1 day', $voted->format('U')));
$canvote = new DateTime($daylater);
$now = new DateTime(date("Y-m-d H:i:s"));
$diff = $canvote->format('U') - $now->format('U');
if ( $diff > 0 && $diff < 86400 ) {
$left = gmdate("H:i:s", $diff);
echo $left . ' left till you can vote again';
} else {
echo 'You can vote again' ;
}
Let me know if it works
Is it not possible to use strtotime() to convert $voteCheck[1] directly? You can then check the unix time stamp against the current time stamp.
This is the flow of commands on my login page
User loads page
php checks if the ip address is in the db, if not it adds it
php checks in the ip address is blocked in the db, if not it proceeds
if it is blocked the script will proceed to get the time the ip was blocked at from the db and calculate the amount of time left until the user can try to login again. The blockout time is 15minutes.
However the problem is that if the user was blocked at 45-59 minutes past the hour then 45+15= 00(as 60 doesn't come up on the time) and any number between 45 and 60 excluding 45 and 60 will go past the hour so for example if i get blocked out at 11:48 i will be unblocked at 12:03.
The problem, if you haven't already figured out is how do i code the countdown timer so it goes past the hour and doesn't spazz out when it goes past 59minutes.
Also i want to do this in php as i have no need to actually present the time left in real-time.
The current minute is never an issue. You are concerned with the duration since last blocked, not with "what time was that":
block_user.php:
<?php
$now = new DateTime();
write_block_into_database($ip_address, $now->format('Y-m-d H:i:s'));
?>
check_block.php
<?php
$sql = 'SELECT 1 FROM sometable WHERE ip_address=? AND DATE_ADD(blocked_at, INTERVAL 1 HOURS) >= NOW()';
if(get_result($sql, $ip_address)) {
// this address is blocked
} else {
// no recent block found
}
Or, if you want to do the comparison in PHP:
check_locally.php:
<?php
$sql = "SELECT blocked_at FROM sometable WHERE ip_address=?";
$db_row = get_row($sql,$ip_address);
if ($db_row) {
$blocked = new DateTime($db_row->blocked_at);
$blocked->modify('+1 hour');
$now = new DateTime();
if ($blocked >= $now) {
// still blocked
} else {
// was blocked earlier, no more
}
} else {
// not blocked
}
In other words: "if I take the time the IP was blocked and add one hour, is now still before that point in time?"
Example:
blocked at 12:48
checking at 13:10: 12:48 + 1 hour = 13:48, 13:48 >= 13:10, fail
checking at 15:10: 12:48 + 1 hour = 13:48, 13:48 < 15:10, pass
This is what I managed to come up with
$date = new DateTime();
$currentTime = $date->getTimestamp();
$blockTime = "1453494620";//This value will be taken from the mysql db
$timeElapsed = $currentTime - $blockTime;
echo "Current Time: $currentTime";
echo "<br>Block Time: $blockTime <br>";
if ($timeElapsed < 900){
$leftTime = ((900 - $timeElapsed) / 60) + 1;
$DotPosition = (stripos($leftTime, ".")) + 1;
if($DotPosition == 3 || $DotPosition == 2){
$leftTime = substr($leftTime, 0, $DotPosition - 1);
}
if($leftTime == 1){
$minutesString = "minute";
} else $minutesString = "minutes";
echo "<br>You are blocked from trying to login for too many incorrect tries.
<br>Please try again in $leftTime $minutesString.";
} else {
/*for test purpose, here the user will get unblocked on the mysql by updating the
ips blockout field */
echo "<br>You have been unblocked.";
}
Current Time: 1453495488
Block Time: 1453494620
You are blocked from trying to login for too many incorrect tries.
Please try again in 1 minute.
Thank you guys for telling me about UNIX Timestamps. If I knew about them I wouldn't have asked. :)