简体   繁体   English

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

[英]PHP Undefined Index When Checking Cookie Value And Cookie Exists

I know to check for the existence of a cookie before I try to use it, but in this case If I set a cookie and then try to use it immediately afterwards without checking, the code works, however I get an "undefined index" warning in my php.log. 我知道在尝试使用Cookie之前会先检查它是否存在,但是在这种情况下,如果我设置一个Cookie,然后尝试立即使用它而不进行检查,则该代码有效,但是我收到“未定义索引”警告在我的php.log中。

The code below determines if the device is a computer or mobile and sets a cookie. 下面的代码确定设备是计算机还是移动设备并设置cookie。 It then checks the cookie value and if a mobile it redirects to a page. 然后,它会检查Cookie值,以及是否将移动设备重定向到页面。 (If not, it will output a page and then show the content within a frame). (如果没有,它将输出页面,然后在一个框架中显示内容)。

<?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']);
}

?>

The only thing I can think of is that it's a timing issue and that the cookie doesn't exist at the time the check is made, however the correct value is obviously retrieved because it works correctly on tablets and phones. 我唯一能想到的是这是一个定时问题,并且在进行检查时cookie不存在,但是显然可以检索到正确的值,因为它可以在平板电脑和手机上正常工作。

Any thoughts? 有什么想法吗? I know it's not a major problem, but it's nice if you can prevent any PHP logging other than REAL errors. 我知道这不是一个主要问题,但是如果您可以阻止除REAL错误以外的任何PHP日志记录,那就很好了。

Ahh Eureka! 啊,尤里卡! The answer finally dawned on me following a similar cookie related problem. 在出现与Cookie相关的类似问题后,答案终于浮现在我身上。

If you set a cookie, you can't check the value in the same cycle of the script, it's only recognizable once the page output has been sent to the browser. 如果设置cookie,则无法在脚本的同一循环中检查该值,只有将页面输出发送到浏览器后才能识别它。

So, in this case I would need to recode the last part of the script, assuming I had just created the cookie. 因此,在这种情况下,假设我刚刚创建了cookie,则需要重新编码脚本的最后一部分。

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

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