在 php 中使用 cookie
我只是想设置和使用 cookie,但我似乎无法存储任何内容。
登录时,我使用:
setcookie("username", $user);
但是,当我使用 Firefox 和 Web Developer 插件 Cookies ->查看 Cookie 信息 没有用户名 cookie。
访问后续页面中的值时,
另外,当我尝试使用$_COOKIE["username"]
它返回 null/空
var_dump(setcookie("username", $user));
结果:bool(true)
和
var_dump($_COOKIE)
结果:特定的 cookie 不存在(其他存在)
我做了更多测试...
登录后(第一页)cookie 存在,但当我转到另一个(第二页)时消失,并且永久丢失...
是是否有任何标题必须存在或不存在?
I'm just trying to set and use a cookie but I can't seem to store anything.
On login, I use:
setcookie("username", $user);
But, when I use Firefox and the Web Developer plugin Cookies -> View Cookie Information There is no username cookie.
Also, when I try to access the value from a subsequent page using
$_COOKIE["username"]
It is returning null/empty
var_dump(setcookie("username", $user));
RESULT: bool(true)
and
var_dump($_COOKIE)
RESULT: specific cookie does not exist (others are there)
I have done some more testing...
The cookie exists after login (first page) but disappears when I go to another (2nd page) and is lost for good...
Are there any headers that must be present or not present?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
http://php.net/manual/en/function.setcookie.php
尝试将 $expire 参数设置为将来的某个时间点。我相信它默认为 0,那是很久以前的事了。
http://php.net/manual/en/function.setcookie.php
Try setting the $expire parameter to some point in the future. I believe it defaults to 0, which is in the distant past.
确保正确设置域参数,以防登录后转到另一个页面后 URL 发生变化。您可以在 http://php.net/manual/en 上阅读有关域参数的更多信息/function.setcookie.php
Make sure that you are setting the domain parameter correctly in case the URL is changing after you go to another page after login. You can read more about the domain parameter on http://php.net/manual/en/function.setcookie.php
cookie 可能已过期,因为
$expire
默认为 Unix 纪元以来的 0 秒。 (docs)尝试
设置后 20 分钟到期 (根据客户的时间)。
The cookie is probably expired because
$expire
defaults to 0 seconds since the Unix epoch. (docs)Try
which expires 20 minutes after set (based on the client's time).
在 setcookie(..) 上使用 var_dump() 查看返回的内容。也可以对 $_COOKIE 执行相同的操作以查看该密钥是否已设置。
Use var_dump() on setcookie(..) to see what is returned. Also might do the same to $_COOKIE to see if the key is set.
感谢大家的反馈...Aditya引导我进一步分析cookie,我发现路径是问题...
登录路径是/admin/,然后我重定向回根...
谢谢大家您的帮助和反馈!
Thanks everyone for the feedback... Aditya lead me to further analyse the cookie and I discovered that the path was the issue...
The login path was /admin/ and then I was redirecting back to the root...
Thanks all for your help and feedback!