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

时间:2014-03-13 10:57:17

标签: php cookies indexing undefined

我知道在尝试使用cookie之前检查是否存在cookie,但是在这种情况下如果我设置了一个cookie,然后尝试立即使用它而不进行检查,代码可以工作,但是我得到了一个&# 34;未定义索引"在我的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日志记录,那就太好了。

1 个答案:

答案 0 :(得分:0)

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

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

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