如何使电子邮件链接在php中X分钟后过期?

时间:2019-03-26 10:08:15

标签: php date

我正在处理的电子邮件链接会在 X 分钟后过期,其中 X 表示某些随机date_time 。因此,我的动机是在我在 $ expire_date 旁边设置date_time之后的一段时间后使链接失效。

所以我只是为了确保我的代码正常工作而自己创建了伪代码。

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

我想我上面的代码中缺少一些内容,如果有人指出正确的方向或更好的实现,上面的代码将无法正常工作。

4 个答案:

答案 0 :(得分:1)

您正在比较无法使用的日期字符串。您必须先将字符串解析为日期时间对象或时间戳,然后才能比较这些值。

例如,使用时间戳记:

$expire_date = "02:59PM 26-Mar-2019"; 

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

答案 1 :(得分:1)

如果要比较PHP中的日期,最好的选择是使用 UNIX时间戳。 UNIX时间戳是自UNIX时代(1970年1月1日星期四,00:00:00)以来的秒数。

time()将返回当前的UNIX时间戳。
strtotime()会将日期字符串转换为UNIX时间戳。

所以替换这两行:

$now = $currentDateTime-> format(' h:iA j-M-Y ');
$expire_date = "02:59PM 26-Mar-2019";

有了这些:

$now = time();
$expire_date = strtotime("02:59PM 26-Mar-2019");

应该解决您的问题。

答案 2 :(得分:1)

您正在将时间作为字符串进行比较。这是行不通的,因为您的第一个格式化字符串有一个前导空格。

相反,请尝试删除空格,或者更好地将时间与DateTime对象进行比较:

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

答案 3 :(得分:0)

您所要做的就是使用strtotime函数并在date函数内部添加,这里您可以指定day, hour, minutes, seconds作为边界。这样,您可以通过添加+5分钟左右的时间来手动设置时间。

date_default_timezone_set("Asia/Kolkata"); // set time_zone according to your location
$created = "2020-08-14 17:52"; // time when link is created 
$expire_date = date('Y-m-d H:i',strtotime('+1 minutes',strtotime($created)));
//+1 day = adds 1 day
//+1 hour = adds 1 hour
//+10 minutes = adds 10 minutes
//+10 seconds = adds 10 seconds
//To sub-tract time its the same except a - is used instead of a +

$now = date("Y-m-d H:i:s"); //current time


if ($now>$expire_date) { //if current time is greater then created time

    echo " Your link is expired";
}
else  //still has a time
{
   echo " link is still alive";
}