PHP在检查Cookie值和Cookie存在时未定义索引


PHP Undefined Index When Checking Cookie Value And Cookie Exists

我知道检查cookie的存在之前,我尝试使用它,但在这种情况下,如果我设置一个cookie,然后尝试使用它之后立即没有检查,代码工作,但是我得到一个"未定义的索引"在我的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在检查时不存在,但是正确的值显然是检索到的,因为它在平板电脑和手机上正确工作。

任何想法吗?我知道这不是一个主要问题,但如果你能防止任何PHP日志除了真正的错误,这是很好的。

啊,找到了!在遇到一个类似的cookie相关问题后,我终于明白了答案。

如果你设置了一个cookie,你不能在脚本的同一循环中检查值,它只有在页面输出被发送到浏览器时才能被识别。

因此,在本例中,我需要重新编码脚本的最后一部分,假设我刚刚创建了cookie。