1

I'm writing a token authentication system for a little project of mine in PHP. A request is made to a script which then generates the token and stores it into a database with an expiry date of the current time +2 minutes.

There is then another script which takes the token in its request, checks it's valid and the token hasn't expired. This is where I'm getting stuck. I'm unable to succesfully compare the two dates and even though the condition should be true, it's not.

Here's how I insert the time into the database;

// Now, we want to gen the token.
$token = randomKey(20);

// Current time + 2 minutes
$time = date("m/d/Y h:i:sa", time() + 120);

// Insert the token into the DB
$obj->query("INSERT INTO `tokens`(`username`, `token`, `expiry`) VALUES ('$uid', '$token', '$time')");

Here's how I attempt to compare them;

if(strtotime($row['expiry']) < strtotime(date("m/d/Y h:i:sa")))

No matter what, even after changing the time in the db to a day in the past, this condition always evaluates to false.

7
  • What kind of format is it being stored in your DB? The a at the end is confusing me, MySQL dates are normally stored in a 24 hour format. Commented Mar 27, 2018 at 9:56
  • If u take DATETIME type in table field then for comparison of dates you need to change the format of database field Commented Mar 27, 2018 at 9:57
  • @ThomasEdwards they're being stored as VARCHARS Commented Mar 27, 2018 at 9:58
  • What is the output of var_dump($row['expiry']);? Commented Mar 27, 2018 at 10:00
  • Consider storing them as dates in MySQL so they arrive as a date format, rather than converting them again. Commented Mar 27, 2018 at 10:00

1 Answer 1

2

Its false because its a non well formatted number.

Try doing echo date("m/d/Y h:i", date("m/d/Y h:i:sa", time());

You will get an error.

Why do you not use unix time stamp instead for both inserting to DB and reading later? So much easier.

$time = date("U") + 120;

// Do DB insert....

if($row['expiry'] < date("U")){
    // Do something...
}
Sign up to request clarification or add additional context in comments.

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.