【问题标题】:php cookies are not setting?php cookie 没有设置?
【发布时间】:2013-07-02 10:42:40
【问题描述】:
<?php
if (!isset($_COOKIE['firsttime']))
{
setcookie("firsttime", "no", time()+1500); 
 ?>

 <div class="row-fluid">
        <div class="span4 center">
        </div>
            <div class="span4 center">
            <div style="">
                    <div class="alert alert-info">
                            <button type="button"     href="<?php setcookie("firsttime", "no", time()+1500); ?>" class="close" data-   dismiss="alert">&times;</button>
                            <strong>Welkom</strong> <br   />Dit is je eerste bezoek op wijktoernooi.nl ! <br /> Wil je je direct registreren? Klik hier!
                    </div>
                    </div>
            </div>
            <div class="span4 center">
        </div>

    </div>
<?php
}
 else
{
// do or show nada !
}
?>

根据上面的代码,如果没有设置 cookie,它应该首先设置 cookie 并显示警告框

但它没有....当我重新加载页面时,我仍然看到警告框,我在哪里犯了错误?

【问题讨论】:

  • 打开错误报告error_reporting(E_ALL); ini_set('display_errors', 1); 我敢打赌你在setcookie() 调用之前有HTML 输出,导致Headers already sent 错误,因为你发送&lt;div&gt;s 无处不在
  • 从您的 href="" 代码中移除 setcookie(必须在发送 html 内容之前使用)。您的代码在我的服务器上运行。您的浏览器启用了 cookie 吗?你的开发环境是什么?
  • 使用 setcookie("firsttime", "no", time()+1500, '/'); 确保它是为整个域设置的 - 我怀疑这会解决您的特定问题,但它可能会对其他页面有所帮助。
  • 您可以使用 firecookie 插件来检查 cookie 发生了什么。很可能这就是@Michael 刚才所说的。
  • 使用 firefox firebug 查看为您的域设置的 cookie,如果没有名称为“fisrttime”的键,则表示设置 cookie 有问题。或 simlpy 尝试使用 print $_COOKIE 进行调试并退出等。

标签: php cookies


【解决方案1】:

您不能在设置 cookie 之前发送输出。您需要了解 HTTP。 所以在你尝试设置一个cookie之前做这个测试:var_dump(headers_sent());。 如果发送了标头,则说明您做错了。

href="&lt;?php setcookie(...); ?&gt;" 是迄今为止对PHP 最有创意的用法。 PHP 打印东西。它不对HTML/DOM/JS 事件做出反应。它接受输入并产生输出。就是这样。

我不能给你任何在这里工作的代码,因为你没有理解它的头部或尾部。所以弄清楚HTTP (客户端/浏览器和服务器/php通信)cookies只有这样你才能修复这个并在未来做正确的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-09
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 2016-08-17
    • 2021-07-03
    • 1970-01-01
    相关资源
    最近更新 更多