【问题标题】:PHP Undefined Index When Checking Cookie Value And Cookie Exists检查 Cookie 值和 Cookie 存在时的 PHP 未定义索引
【发布时间】:2014-03-13 10:57:16
【问题描述】:

我知道在尝试使用 cookie 之前检查它是否存在,但在这种情况下,如果我设置了一个 cookie,然后尝试在没有检查的情况下立即使用它,代码可以工作,但是我得到一个“未定义index”警告在我的 php.log 中。

以下代码确定设备是计算机还是移动设备并设置 cookie。然后它检查 cookie 值,如果是移动设备,它会重定向到一个页面。 (如果没有,它会输出一个页面,然后在一个框架内显示内容)。

<?php
// Determine if computer or mobile device
if (!isset($_COOKIE['devicetype']))
{
require_once 'assets/mobiledetect/Mobile_Detect.php';
$detect = new Mobile_Detect;
$deviceType = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer');
// Any mobile device (phones or tablets).
if( $detect->isMobile() || $detect->isTablet() ){
    setcookie('devicetype', 'mobile',0,'/');
}
else
{
    setcookie('devicetype', 'computer',0,'/');
}
}

// Show flipper page full screen if mobile device
if ($_COOKIE['devicetype'] == 'mobile'){
header('Location: flipping-promotions/'.$_GET['link']);
}

?>

我唯一能想到的是,这是一个时间问题,并且在进行检查时 cookie 不存在,但是显然检索到了正确的值,因为它可以在平板电脑和手机上正常工作。

有什么想法吗?我知道这不是一个大问题,但如果你能防止除 REAL 错误之外的任何 PHP 日志记录,那就太好了。

【问题讨论】:

    标签: php cookies indexing undefined


    【解决方案1】:

    啊,尤里卡!在一个类似的 cookie 相关问题之后,我终于明白了答案。

    如果设置了cookie,则无法在脚本的同一循环中检查该值,只有将页面输出发送到浏览器后才能识别。

    因此,在这种情况下,我需要重新编码脚本的最后一部分,假设我刚刚创建了 cookie。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-09
      • 1970-01-01
      • 1970-01-01
      • 2013-04-22
      相关资源
      最近更新 更多