0

In my code I pretty much send a token to the database with the

date('Y-m-d H:i:s');

function. But I am checking to see if the timestamp I sent if greater than 60 seconds if so i echo yes and else no. I keep getting no and I know its more than a minute because i time it. I've seen post about this but they're using specific dates and I am just going on when a user submits a form and checking if the token is 60 seconds old. Here is my code

php

<?php
    require_once('db_login.php');

    $stmtToken = $handler->prepare("SELECT * FROM email_token");
    $stmtToken->execute();
    $rowToken = $stmtToken->fetch();
    $date = $rowToken['time_stamp'];

     if($date > time() + 60) {
        echo 'yes';
     } else {
        echo 'no';
     }






?>
Jagr
  • 484
  • 2
  • 11
  • 31
  • 1
    Time() is in Unix (integer) and date is a string. If you make your date an integer (Unix) it will be possible to compare – Andreas Feb 24 '18 at 05:51
  • 1
    Is `$date` supposed to be in the future? Or is `$date` in the past? As written, you are asking if `$date` is 60+ seconds into the future from when you are performing the check. – tehhowch Feb 24 '18 at 05:52
  • Possible duplicate of [How to compare two dates in php](https://stackoverflow.com/questions/8722806/how-to-compare-two-dates-in-php) – Andreas Feb 24 '18 at 05:52
  • Well date is the past. I am checking if its been 60 seconds already since it was sent to the database – Jagr Feb 24 '18 at 06:01
  • 1
    In that case your doing it wrong. Try this: `if(strtotime($date) + 60 < time()) {` – Andreas Feb 24 '18 at 06:02
  • I saw that in one of the stack questions. How would you approach this @Andreas – Jagr Feb 24 '18 at 06:03
  • that worked @Andreas can you post it as an answer so i can rate it – Jagr Feb 24 '18 at 06:23

2 Answers2

2

You can also play with dates in different manners. All four lines here are equivalent:

$now = (new \DateTime(date('Y-m-d H:i:s')))->getTimestamp();
$now = (new \DateTime('now'))->getTimestamp();
$now = (new \DateTime())->getTimestamp();
$now = time();

And then you can compare in this manner:

$tokenExpirationTimestamp = (new \DateTime($date))
    ->modify('+60 seconds')
    ->getTimestamp();

$isTokenExpired = $tokenExpirationTimestamp < time();

if ($isTokenExpired) {
    // ...
}
sensorario
  • 20,262
  • 30
  • 97
  • 159
1

When you compare times and dates you can either use datetime or strtotime.
Using strings will not work as expected in all cases.
In comments you mentioned how you want to compare, and you need to add the 60 seconds to the "date", not the time().

if(strtotime($date) + 60 < time()) {
Andreas
  • 23,610
  • 6
  • 30
  • 62