Skip to content
Advertisement

How to make email link expire after X minutes in php?

I am working on email link expire after some X minutes where X denotes some random date_time. so my motive is to expire the the link after some time what ever I set the date_time in side the $expire_date.

So I just created dummy code myself just in order to sure my code works or not.

$currentDateTime = new DateTime(); 
$currentDateTime-> setTimezone(new DateTimeZone('Asia/kolkata'));
$now = $currentDateTime-> format(' h:iA j-M-Y ');
$expire_date = "02:59PM 26-Mar-2019"; 

if($now > $expire_date) 
{ 
    echo " link is expired"; 
}
else{ 
    echo " link still alive "; 
}

I guess I am missing something in the above code, somehow the above code isn’t working if anyone would point out the right direction or some better implementation it would be great.

Advertisement

Answer

You are comparing the times as strings. This does not work, as your first formatted string has a leading space.

Instead, try either removing the whitespace, or better, compare the times as DateTime objects:

$timezone = new DateTimeZone('Asia/kolkata');

// Create the current DateTime object
$currentDateTime = new DateTime(); 
$currentDateTime-> setTimezone($timezone);

// Create the given DateTime object
$expire_date = "02:59PM 26-Mar-2019"; 
$expireDateTime = DateTime::createFromFormat($expire_date, 'h:iA j-M-Y');

// Compare the objects
if($currentDateTime > $expireDateTime) 
{ 
    echo " link is expired"; 
}
else{ 
    echo " link still alive "; 
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement