检查Cookie值和Cookie是否存在时,PHP未定义索引 [英] PHP Undefined Index When Checking Cookie Value And Cookie Exists

查看:168
本文介绍了检查Cookie值和Cookie是否存在时,PHP未定义索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在尝试使用cookie之前会先检查它是否存在,但是在这种情况下,如果我设置一个cookie,然后尝试不经检查立即使用它,那么代码会起作用,但是我得到了未定义索引中的警告。

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值,以及是否将移动设备重定向到页面。 (否则,它将输出页面,然后在一个框架中显示内容。)

The code below determines if the device is a computer or mobile and sets a cookie. It then checks the cookie value and if a mobile it redirects to a page. (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']);
}

?>

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

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.

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

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.

推荐答案

Ahh Eureka !

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值和Cookie是否存在时,PHP未定义索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆