【问题标题】:Finding Cookie Expiry Time in PHP?在 PHP 中查找 Cookie 过期时间?
【发布时间】:2014-01-24 19:25:28
【问题描述】:

我想查看我的 cookie 过期时间。

我的代码是这样的:

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

但我想在刷新页面时查看 cookie 的过期时间。这个怎么办?

【问题讨论】:

    标签: php cookies setcookie


    【解决方案1】:

    除非您将该信息编码为 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!');
    }
    

    【讨论】:

      猜你喜欢
      • 2011-12-17
      • 2011-09-20
      • 2012-07-25
      • 2011-01-05
      • 2013-07-06
      • 2017-06-23
      • 1970-01-01
      • 2017-01-11
      • 2012-12-12
      相关资源
      最近更新 更多