Reputation: 23
I am making an API in which I need to check the token validity for a particular user and for that I am using DateTime function of php. I am saving a token and current time on login and I want token to be valid for 10 minutes, so when a user makes a request within first 10 minutes of its login I want to update the time validity of token.
$currentTime = new DateTime();
$curTime = $currentTime->format("Y-m-d H:i:s");
$time10MinutesAgo = new DateTime("10 minutes ago");
$time10Minutes = $time10MinutesAgo->format("Y-m-d H:i:s");
$token_time = $query1_r['token_time']; // value is stored in the db(mysql)
if (($curTime > $token_time) && ($token_time >= $time10Minutes)){}
first I was unable to pass the second condition but now even my page is not working.
Upvotes: 1
Views: 144
Reputation: 43552
If you already have DateTime object, don't convert them to strings, just compare objects between each other, like this:
$currentTime = new DateTime();
$time10MinutesAgo = new DateTime("10 minutes ago");
$tokenTime = new DateTime($query1_r['token_time']);
if ($time10MinutesAgo <= $tokenTime && $tokenTime <= $currentTime) {
echo "Token time is between now and now-10 minutes.";
}
Upvotes: 1
Reputation: 4243
Use epoch time values for time comparisons it's much easier to compare numbers instead of dates.
$currentTime = time();
$time10MinutesAgo = strtotime('-10 minutes');
$token_time = strtotime($query1_r['token_time']); // value is stored in the db(mysql)
if(($currentTime >$token_time) && ($token_time >= $time10MinutesAgo )){}
Upvotes: 2