1

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.

12
  • 1
    $curTime and $token_time and $time10Minutes are strings, and not DateTime objects. Commented Mar 18, 2018 at 7:10
  • how can I make it work ? Commented Mar 18, 2018 at 7:11
  • @u_mulder why comparing $time10MInuteAgo and $token_time is creating a problem ? Commented Mar 18, 2018 at 7:29
  • What problem it creates? Commented Mar 18, 2018 at 7:33
  • @u_mulder ($curTime > $token_time) this condition is working fine and ($token_time >= $time10Minutes) this condition is not working. Commented Mar 18, 2018 at 7:36

2 Answers 2

2

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 )){}
Sign up to request clarification or add additional context in comments.

3 Comments

Actually I was Date function before and was converting them to timestamp but that process was taking more time, plus my main concern is why comparing $time10MInuteAgo and $token_time is creating a problem ?
@PrakharSharma I wouldn't ever use string comparisons for time, much easier with integer comparisons with epoch formatting.
@PrakharSharma you're welcome, please accept my answer :)
1

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.";
}

demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.