【问题标题】:Checking for cookies results in an error in PHP检查 cookie 会导致 PHP 出错
【发布时间】:2014-04-18 16:54:38
【问题描述】:

我试图创建一个系统,通过用 PHP 编写的 cookie 检查您之前是否访问过该网站,或者您是否是新用户。

代码:

<?php
if(isset($_COOKIE['cookie'])) {                 //Checking for cookie, this is line 2
    echo "You have visited before";
}else{                                          //If there is no cookie
    echo "Welcome to this site!";
    setcookie("cookie", "cookie_is_set", );     //Setting cookie because user has visited
};

当我运行此代码时,我收到以下错误:

注意:未定义的索引:第 2 行 C:\Apache24\htdocs\cookietest\index.php 中的 cookie

查看其他人的代码后,我怀疑这是我的 PHP 中的一些错误或什么的原因......所以我应该禁用它还是什么,以及如何?还有其他问题吗?

感谢您提前回答,San Bergam

【问题讨论】:

  • 如果你明确地将 $_COOKIE['cookie'] 设置为某个东西然后测试 isset,你会得到错误吗?
  • 我认为您可能正在查看错误的代码,您的代码中没有引用 ['fun'] 索引。
  • 输入正确的代码@San Bergam

标签: php cookies setcookie


【解决方案1】:

您的代码似乎没有错误。在您的错误消息中,“注意:未定义的索引:有趣”。但是在您的代码中,我没有看到“有趣”的索引。

我们有两种方法来检查 cookie 是否存在

if(isset($_COOKIE['cookie'])){
    $cookie = $_COOKIE['cookie'];
}
else{
    // Cookie is not set
}

if(array_key_exists('cookie', $_COOKIE)) {
    $cookie = $_COOKIE['cookie'];
} else {
    // Cookie is not set
}

【讨论】:

    【解决方案2】:

    无论如何,您的代码存在与索引“有趣”无关的问题。如果您在 Window 上进行测试,结果也很可能会被缓存在浏览器和操作系统中。我在 Windows 上测试时经常遇到这个问题。

    你的错误:

    setcookie("cookie", "cookie_is_set", );

    根据说明书

    http://www.php.net/manual/en/function.setcookie.php

    bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

    您可以传递名称和字符串值,cookie 将在会话结束时过期,通常是在浏览器关闭时,或者在浏览器打开时手动清除缓存。

    if(isset($_COOKIE['cookie'])) {
        echo "You have visited before";
    } else {
        setcookie("cookie", "cookie_is_set", 0);
        echo "Welcome to this site!";
    }
    

    如果您在 windows 或 *nix 中使用 php -a 将代码放入控制台,则会打印消息 "Welcome to this site!"。如果您将其放入 php 文件中,也会发生同样的情况,例如。 index.php,但在后续刷新时,将显示消息"You have visited before"

    【讨论】:

      猜你喜欢
      • 2014-10-11
      • 1970-01-01
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-16
      • 2016-07-05
      相关资源
      最近更新 更多