I am creating a new website and so far everything is working perfect but I have one small issue and i am wondering if anyone knows a way to sort it out.
Users come to my site to generate pin codes for my applications now this works perfect the pins are saved to a db with a created_at time and then an expires_at time with is creation time + 3 hours.
It works perfect most of the day but I run into issues when it gets to about 9:30 pm every day.
When you create a pin around 9:30 the creation time will be:
9:23:43
Now then expiration time will be
00:23:43
and this is where the issue is when they add the pin to my applications. It checks them from the database by comparing the current time by creation time using the code below:
<?php
include 'inc.db.php';
include 'inc.clear.php';
date_default_timezone_set('Europe/London');
function Check($key, $pin){
global $mysqli;
$time = date("H:i:s");
$stmt = $mysqli->prepare("SELECT expired FROM tbl_pins WHERE key=? AND pin=?");
$stmt->bind_param('ss', $key, $pin);
$stmt->execute();
$stmt->bind_result($expired);
while($stmt->fetch()) {
if($time >= $expired){
$result = 'Pin Expired';
Clear($pin);
}else{
$result = 'Pin Verified';
}
}
$stmt->close();
return $result;
}
?>
but as it checks the pin, the current time will be
22:10:30 and it checks to see if this is above the expiration time but that's 00:24:22 so because it's after 12am, it's always a lower number.
Does anyone know a way around this?
Use Unix Epoc time
time()
Expiration will be Three hours from now:
time() + (3 * 60 * 60)
Expired true if
time() > Expiration
Use date as well in both created_at and expired_at. If one creates at 1AM and expires at 4AM, do you think 2AM tomorrow (or next year) is still valid? Without date, time is not enough for token expirations for sure.
Related
I'm using a time clock system which, by default, records only the employee's entry and exit times. I'm customizing it so that it's possible to also record break times but I'm having trouble getting the break time to be subtracted from the total time.
This snippet of code is used to register the time between the check-in and check-out:
$time1 = Carbon::createFromFormat("Y-m-d H:i:s", $timeIN);
$time2 = Carbon::createFromFormat("Y-m-d H:i:s", $timeOUT);
$th = $time1->diffInHours($time2);
$tm = floor(($time1->diffInMinutes($time2) - (60 * $th)));
$totalhour = ($th.".".$tm);
The variable ($totalhour) receives the total value between the input register and the output register. It sends to the database in H.i format (hour.minutes), then another page searches for this information in the database and replaces the point (.) with (hr).
Based on this code, I did the same to get the interval start and end timestamps. I was able to get the time between the start time and end time interval with the code below:
$breakstart = table::attendance()->where([['idno', $idno]])->value('breakstart');
$breakend = table::attendance()->where([['idno', $idno]])->value('breakend');
$one = Carbon::createFromFormat("H:i:s", $breakstart);
$two = Carbon::createFromFormat("H:i:s", $breakend);
$breakone = $one->diffInHours($two);
$breaktwo = floor(($one->diffInMinutes($two) - (60 * $breakone)));
$totalbreak = $breakone.".".$breaktwo;
The $totalbreak variable stores the time taken between the start and end of the break. I was also successful in getting the time between this interval.
Now, I need the total time to be done by subtracting the time obtained from the record at the beginning of the interval to the record at the end of the interval.
I did with this code and got good result up to a point. Could you give me tips on how to get an assertive result in this case?
$totalhour = ($th.".".$tm) - ($totalbreak);
I tried to get the total time by subtracting the break time, but without success.
I am making a game mode in which I am trying to get the time a player has arrived at their destination after starting the mode and to do this I am using the insert of a date when it starts the mode it inserts a date and after reaching the your destination it registers another date and with both dates it calculates the time it took to get to the destination, with this I'm using date H:i:s (hours, minutes, seconds) but I need to take the time out and leave milliseconds after seconds example: i:s:u (minutes, seconds, milliseconds) but I'm not able to do this, I've tried it in several ways, basically everything works as follows:
1. I add in the player array a current date with hour, minutes, seconds;
$this->game[$player->getName()] = ["start" => strtotime('now')];
2. After the Player arrives at his destination he calculates the time of his trajectory creating another current date with already registered and using date and mktime to do the join and give a visual of time to the player;
$time = date('H:i:s', mktime(0, 0, str_replace("-", "", $this->game[$player->getName()]["start"] - strtotime('now'))));
3. Send the pretty message to the player about the time of his trajectory then time will be something like this: 01:45:23 (minute:seconds:milliseconds).
$player->sendMessage("You beat your time record by ".$time);
This is my method of doing, if you have another better method with the milli seconds added I accept the suggestion! Maybe there might be some errors in my code that I'm still not sure if they work correctly as the subtraction to calculate and join the current time with the previous one, tell me if it's right and if it is not correct correct me or do better. Thank you
Use microtime which returns the current Unix timestamp with microseconds
$game = [];
$game['start'] = microtime(true);
// Do stuff
sleep(3); // Without the sleep, start and end are the 'same'
$game['end'] = microtime(true);
$elapsedTime = ($game['end'] - $game['start']);
$minutes = floor($elapsedTime / 60);
$seconds = $elapsedTime % 60;
$milliseconds = number_format($elapsedTime - floor($elapsedTime),3);
I have HTML form which I don't want users to be able to use more then once per day.
So far iv'e figured out what I should do but I'm not really sure how.
When a user submits the form I store their "IP" (column ip) aswell as the current time (column submitTime) and the current time + 23 hours (column releaseTime):
$submitDate = date("Y-m-d H:i:s");
$currentTime = time();
$releaseTime = date("Y-m-d H:i:s", strtotime('+23 hour', $currentTime));
But what I dont know is how can I proceed? I feel like I'm stuck.
I know I should compare $currentTime with the releaseTime I get from MySQL, but how?
So far I got this code (see the comment lines):
$ip = $_SERVER['REMOTE_ADDR'];
$stmt1 = $conn->prepare('SELECT * FROM IPlock WHERE ip=?') or die('Couldn\'t check the IP');
$stmt1->bind_param("s", $ip);
$stmt1->execute();
$stmt1->store_result();
$countRows = $stmt1->num_rows;
$stmt1->close();
if ($countRows > 0) {
/*
Code to check for how long the IP has existed in MySQL
If it has existed for more then 23 hours, remove it and proceed.
else abort (since its blacklisted for another x hours)
*/
}
I know I should not use the IP to identify an user since some users share their IP, but in this case I really have to.
You can use this to check if one has submitted the form in the last 24 hours.
SELECT * FROM IPlock WHERE `ip`=? AND `submitTime` > NOW() - INTERVAL 24 HOUR;
If IP has not submitted in the past 24 hours, no rows will be returned.
EDIT:
In addition to that, there's no need to use PHP date() function, you can do your insert like
INSERT INTO IPlock (`ip`, `submitTime`) VALUES ('127.0.0.1', NOW());
Note that CURRENT_TIMESTAMP will work just as well.
In fact, your problem is different from what you asked.
To compare a datetime value of mysql format you just have to compare it - not a big deal.
The real question is how to get the value for comparison (with your current code you can't) and what to do if you found that the record is outdated.
So, first you need to fetch the datetime value:
$stmt1 = $conn->prepare('SELECT releaseTime FROM IPlock WHERE ip=?');//never use die()
$stmt1->bind_param("s", $_SERVER['REMOTE_ADDR']);
$stmt1->execute();
$stmt1->store_result();
$stmt1->bind_result($releaseTime);
$stmt1->fetch();
and now you can start checking the date. Note that you don't need the num rows here.
if ($releaseTime > date("Y-m-d H:i:s")) {
/*
Code to check for how long the IP has existed in MySQL
If it has existed for more then 23 hours, remove it and proceed.
else abort (since its blacklisted for another x hours)
*/
}
I´m making a simple time management system feature and I want to add
task and estimated minutes.
So if I add into the field "finish sending e-mail to John" and "23" (as minutes) it goes into
mysql as $sql = "INSERT INTO schedule (task, time, timestamp) VALUES ('$_POST[task]','$_POST[time]','$_POST[timestamp]')";
The output would be " Finish sending e-mail to John 21:02 - 21:25 "
so if next task takes 7 minutes it will be from 21:26 - 21:33" (take notice
of the first task and so and and so forth
I tried echo date('H:i', strtotime('+["time"] minutes', ));
but it doesn´t
work and I don´t know how the next record would take notice of the next one
is this possible?
What you tried above is almost correct, except that you might mean $_POST['time'] instead of ["time"], making your code: echo date ('H:i', strtotime('+{$_POST["time"]} minutes'));. But that will give you the time minutes after current time, not after the starting time.
To get the end time, you need to convert your start time (I assume it's $_POST['timestamp']) into UNIX timestamp, then add the task's length and get the UNIX timestamp from it.
Give this a try:
// Remember to check for valid user input. I'll leave that for you.
$task = $_POST['task'];
$time = $_POST['time'];
$timestamp = $_POST['timestamp'];
// Get the time here
$start_time = date ("H:i", strtotime ($timestamp));
$end_time = date ("H:i", strtotime ($timestamp) + $time * 60);
echo "{$task} {$start_time}-{$end_time}\n";
Is there a simple straight forward way to find the remaining time between a start date - ex: 2013-01-10 12:34:55 and 5 minutes later?
What I mean is I have the start date and want to check that 5 or 60 minutes later gives a time difference of 0. Kind of a time out to be checked on server side.
You have 2 dates, correct ?
$date1 = strtotime('2013-01-10 12:34:33'); // converto to time
$date2 = strtotime('2013-01-10 12:45:33'); // or else it won't work
$diff = date('u', $date1) - date('u', $date2); // the difference in seconds between the two
// if you want $date2 to be now, just use date('u')
if ($diff > 3600) { // an hour later
echo 'The difference between $date1 and $date2 is more than an hour';
}
If you want to do something like "session time out" for the user. Use Javascript setintervel() and do ajax() call to logout user from the application.
Well, seems like I was going the harder way... found that it would be easier and more reliable to get it from an sql check than in php.
I've implemented this with success. Leave it here just in case it might be useful.
$query = "SELECT * FROM db_table
WHERE DATE_ADD(my_start_date, INTERVAL 5 MINUTE) > NOW()";
Where 5 is the interval that can be set in seconds (SECOND), minutes (MINUTE), hours (HOUR), days (DAY) etc.