PHP - 以分钟为单位显示链接到期时间

时间:2015-06-21 17:58:17

标签: php

我想用php设置一个链接到期日期:

我希望当用户在我的网站上创建新的短链接时,它应该在创建的第五天自动删除。

我对以下代码感到困惑。我想将此代码放在用户的通知页面上,以便它可以通知他们为链接过期需要多少分钟。

<?php 
$created=time();
$expire=$created + 5;
$total_minutes=$expire / 5 / 60;
echo "Link expires in $total_minutes minutes";?>

输出意外的长号码。

如何实现此代码以便输出7200或剩余分钟?

3 个答案:

答案 0 :(得分:1)

time()返回UNIX时间戳。

如果您想要人类可读的输出,请查看PHP中的DateTime类:http://php.net/manual/en/class.datetime.php

示例:

<?php

$created = new DateTime('now');
$expiration_time = new DateTime('now +5minutes');
$compare = $created->diff($expiration_time);
$expires = $compare->format('%i');

echo "Your link will expire in: " . $expires . " minutes";

?>

答案 1 :(得分:1)

<?php
$created = strtotime('June 21st 20:00 2015'); // time when link is created
$expire = $created + 432000; // 432000 = 5 days in seconds
$seconds_until_expiration = $expire - time();
$minutes_until_expiration = round($seconds_until_expiration / 60); // convert to minutes
echo "Link expires in $minutes_until_expiration minutes";
?>

请注意,$ created不应该在脚本运行时创建,而是保存在某个地方,否则此脚本将始终报告链接在5天后过期。

答案 2 :(得分:1)

php函数time()以秒为单位返回(自Unix Epoch以来)。

你添加&#34; 5&#34;只有五秒钟。

五天你需要加上5 * 24 * 60 *60的总和,这是五天的秒数。

在代码中:

$created = time();
$expires = $created + (5 * 24 * 60 * 60);

if ($expires < time()) {
    echo 'File expired';
} else {
    echo 'File expires in: ' . round(((time() + 1) - $created) / 60) . ' minutes';
}

请参阅PHP: time()