我们可以根据客户的时间在php中设置cookie吗?

Sha*_*s88 14 javascript php cookies

我有以下要求:

  1. 为服务器域创建一个cookie
  2. 该cookie将在x秒内到期,比如200或500秒.

问题是,客户端可能落后于服务器多少分钟.在服务器端,我将cookie设置为

setcookie($cooName,$cooVal,time()+500,"/");
Run Code Online (Sandbox Code Playgroud)

但是现在如果客户端计算机比服务器落后500秒,则上面的代码将生成一个cookie,该cookie将在1000秒内到期,而不是500秒.

我当时想把客户的时间戳发送到服务器并在那个时候设置cookie.这样的事情:

setcookie($cooName,$cooVal,$_GET['clientTS']+500,"/");
Run Code Online (Sandbox Code Playgroud)

但是如果客户端落后500秒,如果我设置了这样一个已经过时的cookie,它就不会被设置.如果cookie过期,如何在客户端和服务器之间实现时间同步?

Gum*_*mbo 11

不幸的是,Expires是一个绝对日期,取决于用户代理的本地日期.正确结束后,这可能导致cookie过期不准确.

这也是IETF首次对Netscape的原始提案进行标准化的原因,将绝对到期日期替换为相对到期日期,Max-Age属性指定了从发布cookie的时间点开始的delta时间内的时间.RFC 2965,已废弃的RFC 2109,也做了同样的事情.就像RFC 6265一样,这是目前最新的cookie规范.

根据RFC 6265的Cookie也允许使用Max-Age的相对日期和使用Expires的绝对日期来指定到期日期,后者主要用于向后兼容:

如果cookie同时具有Max-Age和Expires属性,则Max-Age属性具有优先权并控制cookie的到期日期.

所以你可以编写自己的函数来模仿这种行为:

$maxage = 12345;
$expires = date(DATE_COOKIE, time()+$maxage);
header("Set-Cookie: $name=$value, Expires=$expires, Max-Age=$maxage, …");
Run Code Online (Sandbox Code Playgroud)

这是一个示例函数:

function set_cookie($name, $value=null, $maxage=null, $path=null, $domain=null, $secure=false, $httponly=false) {
    $cookie = rawurlencode($name) . '=' . rawurlencode($value);
    $attributes = array();
    if (!is_null($maxage)) {
        $maxage = intval($maxage);
        $attributes[] = 'Expires='.date(DATE_COOKIE, $maxage > 0 ? time()+$maxage : 0);
        $attributes[] = 'Max-Age='.$maxage;
    }
    if (!is_null($path)) {
        $attributes[] = 'Path='.rawurlencode($path);
    }
    if (!is_null($domain)) {
        $attributes[] = 'Domain='.rawurlencode($domain);
    }
    if ($secure) {
        $attributes[] = 'Secure';
    }
    if ($httponly) {
        $attributes[] = 'HttpOnly';
    }
    header('Set-Cookie: '.implode('; ', array_merge(array($cookie), $attributes)), false);
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,我遇到了IE的障碍.不支持max-age !! 为什么上帝在这个星球上保持像IE一样邪​​恶的东西!! :'( (2认同)