简体   繁体   English

在PHP中查找Cookie到期时间?

[英]Finding Cookie Expiry Time in PHP?

I want to see my cookie expiry time. 我想看看我的cookie到期时间。

My Code is like this : 我的代码是这样的:

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

But I want to see the cookie expiry time whenever I am refreshing the page. 但是每当我刷新页面时,我都希望看到cookie的到期时间。 How do to this? 怎么做?

You cannot get the cookie expiry time unless you encode that information as part of the cookie (the browser, who has this information, does not send it over). 您无法获得cookie到期时间,除非您将该信息编码为cookie的一部分(浏览器,具有此信息但不发送)。 For example: 例如:

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

Even then, someone could theoretically tamper with the cookie contents so you cannot really "trust" the value unless the cookie contents are also cryptographically authenticated with a HMAC . 即便如此,有人理论上可以篡改cookie内容,因此除非cookie内容也通过HMAC加密认证,否则您无法真正“信任”该值。

An example of how to sign and authenticate the contents of the cookie: 如何签名和验证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);

When you get back the contents of the cookie, strip out and validate the HMAC part: 当您取回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!');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM