我正在尝试创建一个将在 1 小时后过期的按钮或链接。
我正在使用cookie设置访问者点击页面的时间。
我看到的大多数代码示例只给出了过去的时间,而不是剩余的时间。
示例:链接将在 0 小时 30 分钟和 34 秒后过期
这只是一些粗略的代码:
//Setting cookie example
setcookie('previous_time', time(), time()+3600*1);
$current_time = time();
$previous_time = $_COOKIE['previous_time'];
$time_diff = $current_time-$previous_time;
这就是我卡住的地方,我不知道如何转换$time_diff
时间戳转换为"在 0 小时 30 分 34 秒后过期"之类的格式
非常感谢。
要格式化您的时差,只需做一些数学运算,因为您的$time_diff
只是两个时间之间的秒数:
$hours = floor( $time_diff / 3600);
$minutes = floor( ($time_diff / 60) % 60);
$seconds = $time_diff % 60;
echo "$hours hours, $minutes minutes, $seconds secondsn";
因此,20712
值将产生:
5 hours, 45 minutes, 12 seconds
使用比较时间戳的公式,差异以秒为单位。
因此,$time_diff/60 得到分钟;再除以 60 得到小时;等等。
我同意 nickb 的观点,即基于 cookie 是可篡改的,但说您在链接过期时提前一个小时以某种方式标记第一次访问:
// set when we are counting down to
setcookie('expires_at', time()+3600, time()+3600);
// we are counting down not up (for "expires in" not "valid since" logic)
$time_diff = $_COOKIE['expires_at'] - time();
$minutes = floor($time_diff / 60);
$seconds = floor($time_diff % 60);
// zero hours since the link will only be valid for one hour max
echo sprintf('expire in 0 hours, %d mins and %d seconds', $minutes, $seconds);
然后你可以做:
if($time_diff > 0){
echo '<a href="...">...</a>';
}