简体   繁体   English

setcookie()不在本地设置cookie

[英]setcookie() does not set cookie locally

I have a script that should be setting a cookie. 我有一个应该设置cookie的脚本。 On a webserver, it works just fine, however when I test it locally, it does not set. 在网络服务器上,它可以正常工作,但是当我在本地测试时,它没有设置。

The excerpt: 摘录:

setcookie('sid', 'nv48thnuf39sonv', 0, '/', $_SERVER['HTTP_HOST']);

echo isset($_COOKIE['sid']) ? $_COOKIE['sid'] : '(empty)';

There is no output prior to the call of setcookie . 在调用setcookie之前没有输出。

On the server it says (empty) on the first load and nv48thnuf39sonv on the second load (expected behavior). 在服务器上,它在第一次加载时说(empty) ,在第二次加载时说nv48thnuf39sonv (预期行为)。 Via http://localhost/ , however, it says (empty) and never changes regardless of how many time I mash F5 但是,通过http://localhost/ ,它显示为(empty)并且无论我将F5混搭多少次都不会更改

Does anyone know what might be causing cookies to not be set? 有谁知道可能会导致无法设置Cookie的原因?

It's your cookie domain. 这是您的Cookie域。

It requires at least two dots ( . ) or your browser will consider it invalid, thus not storing the cookie. 它至少需要两个点( . ),否则您的浏览器会认为它无效,因此不存储cookie。 The easiest way to get around it is to simply set the cookie domain to null when your $_SERVER['HTTP_HOST'] is localhost: 解决此问题的最简单方法是,当$_SERVER['HTTP_HOST']为localhost时,只需将cookie域设置为null

$cookieDomain = $_SERVER['HTTP_HOST'] == 'localhost' ? null : $_SERVER['HTTP_HOST'];
setcookie('sid', 'nv48thnuf39sonv', 0, '/', $cookieDomain); 
echo isset($_COOKIE['sid']) ? $_COOKIE['sid'] : '(empty)';

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

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