虽然标题看起来正确,但PHP setcookie无法正常工作

时间:2016-06-28 10:55:23

标签: php php-5.6

我正在处理一个帖子请求,设置一个cookie,然后像这样重定向用户:

// (handle post request)

// all fine so set cookie
$ciphertext = Crypto::encrypt($_POST['soulmates_member_id'], Key::loadFromAsciiSafeString($this->encryption_key));
$expires = 60 * 60 * 24 * 30;
setcookie('soulmates_member_id', $ciphertext, $expires, '/', $_SERVER['HTTP_HOST']);

// redirect
header("Location: ".$_POST['soulmates_redirect']);

返回以下回复:

HTTP/1.1 302 Found
Date: Tue, 28 Jun 2016 10:53:21 GMT
Server: Apache/2.4.17 (Win32) OpenSSL/1.0.2d PHP/5.6.21
X-Powered-By: PHP/5.6.21
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Cache-Control: no-cache, must-revalidate, max-age=0
Pragma: no-cache
Access-Control-Allow-Origin: http://local.wordpress.com
Access-Control-Allow-Credentials: true
X-Robots-Tag: noindex
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Set-Cookie: soulmates_member_id=def5020032ce3903334d3564b22303993dc3bd5923256632200d94785aa9cd09a44091a124848bd4476768eb5027082b01ec4036c4fa366ba41613157d548285d8cbee1b1115b0fc3ec454127e62732db13fb72b4ff385eceeae1b7af7c1; expires=Sat, 31-Jan-1970 00:00:00 GMT; Max-Age=-1464519202; path=/; domain=local.wordpress.com
Location: http://local.wordpress.com/another-page/
Content-Length: 0
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8

但是cookie没有设置好。我已经在Chrome和Firefox中尝试了这个功能,但由于某些原因,Cookie无法设置。

1 个答案:

答案 0 :(得分:3)

我解决了!这是因为到期时间需要相对于现在,所以到期日期和时间是这样的:

$expires = time() + 60 * 60 * 24 * 30;