繁体   English   中英

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

[英]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不存在,但是显然可以检索到正确的值,因为它可以在平板电脑和手机上正常工作。

有什么想法吗? 我知道这不是一个主要问题,但是如果您可以阻止除REAL错误以外的任何PHP日志记录,那就很好了。

啊,尤里卡! 在出现与Cookie相关的类似问题后,答案终于浮现在我身上。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM