【问题标题】:Cookies being created but unable to echo them正在创建 Cookie 但无法回显它们
【发布时间】:2013-01-04 00:24:30
【问题描述】:

在我的注册脚本结束时,我设置了一个“登录”的 cookie,就像这样

setcookie("登录", $username, time()+60*60*24*30 );

然后只是重定向回主页。

我正在尝试回显该 cookie 的内容。当我右键单击 > 页面信息 > 安全 > 查看 cookie 时,我可以看到它已创建。

cookie 的名称在那里,“登录”,内容设置为我注册的用户名。但是当我做类似的事情时

print_r ($_COOKIE);

没有显示。

做一个

var_dump($_COOKIE);

给予

array (size=0)
  empty

如果我按照前面提到的步骤可以看到 cookie 确实存在,为什么会发生这种行为?

【问题讨论】:

  • 您是否尝试在重定向之前在同一个脚本上回显cookie? $_COOKIE 在下一个 HTTP 请求之前不会被填充。
  • 查看cookie时,路径说明了什么?当您访问服务器上的 cookie 时,您尝试使用哪些路径?
  • @MichaelBerkowski 不,我将用户添加到数据库,创建 cookie,然后重定向。然后我试图在用户被重定向到的页面上回显 cookie。
  • @nickb 我之前没有设置路径。由于下面的答案,这已得到纠正,现在正在正确回显。

标签: php


【解决方案1】:

通常可能是因为您没有设置域/路径项。尝试使用:

setcookie("loggedin", $username, time()+60*60*24*30, '/', $domain);

【讨论】:

  • 啊,是的,这很好用。但是'/'是否意味着cookie只能在索引页面上查看?
  • 来自 php.net setcookie The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.
  • 我一定错过了。谢谢大家!
  • 没问题,这就是这个网站的用途。
【解决方案2】:

您应该在任何输出之前存储 cookie

因为 cookie 包含在 http 标头中,所以如果您开始输出 html 页面并在此之后存储 cookie - 将不会存储任何内容

【讨论】:

    猜你喜欢
    • 2022-08-23
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    相关资源
    最近更新 更多