Skip to content
Advertisement

PHP Compare 2 Timestamps Logic

I’m working with an API that generates a token that I use for subsequent requests that is valid for 15 minutes. I’m storing a timestamp when the token is first generated and adding 15 minutes to this and storing that as a session variable like this:

// Get current timestamp
$currentTimestamp = date("m/d/Y h:i:s A");
// 07/28/2022 10:37:05 AM

// Add 15 minutes to current timestamp
$expiryTimestamp = date('m/d/Y h:i:s A', strtotime($currentTimestamp)+15*60); 
// 07/28/2022 10:52:05 AM

$_SESSION['tokenExpiryTimestamp'] = $expiryTimestamp;   

When I make a subsequent call to the API I’m checking to see if the token will have expired by then:

if( strtotime($currentTimestamp) < strtotime($_SESSION['tokenExpiryTimestamp']) ){
    // Token Still Valid  
}else{
    // Token Has Expired
}

Is there any flaws in this logic (e.g. doing a string comparison instead of a timestamp comparison) or a better way to compare timestamps here to see if the token has expired?

Advertisement

Answer

You’re not interested in the actual date or time. You just want to know if 15 minutes have passed since some point in time. There’s no need to mess about with conversions to human readable formats. Just use time() and add 900:

$_SESSION['tokenExpiryTimestamp'] = time()+900;

Then

if (time() < $_SESSION['tokenExpiryTimestamp']) {
    // Do some stuff
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement