在PHP中查找Cookie到期时间?

时间:2013-07-04 08:51:26

标签: php cookies setcookie

我希望看到我的Cookie到期时间。

我的代码是这样的:

setcookie('blockipCaptcha','yes',time() + (86400 * 7));

但是每当我刷新页面时,我都希望看到cookie的到期时间。怎么做?

1 个答案:

答案 0 :(得分:4)

除非您将该信息编码为cookie的一部分(浏览器,具有此信息但不发送该信息),否则您无法获得Cookie到期时间。例如:

$expiresOn = time() + (86400 * 7);
setcookie('blockipCaptcha','yes;expires=' . $expiresOn, $expiresOn);

即便如此,理论上有人可能会篡改cookie内容,因此您无法真正“信任”该值,除非Cookie内容也使用HMAC进行加密身份验证。

如何签名和验证cookie内容的示例:

$secretKey = ''; // this must be a per-user secret key stored in your database
$expiresOn = time() + (86400 * 7);
$contents = 'yes;expires=' . $expiresOn;
$contents = $contents . ';hmac='. hash_hmac('sha256', $contents, $secretKey);

当您取回cookie的内容时,删除并验证HMAC部分:

$contents = $_COOKIE['blockipCaptcha'];

// I 'm doing this slightly hacky for convenience
list ($contents, $hmac) = explode(';hmac=', $contents);

if ($hmac !== hash_hmac('sha256', $contents, $secretKey)) {
    die('Someone tampered with the contents of the cookie!');
}
相关问题