PHP Undefined Index When Checking Cookie Value And Cookie Exists

馋奶兔 提交于 2019-12-25 02:49:06

问题


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.

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

?>

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.

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.


回答1:


Ahh Eureka! The answer finally dawned on me following a similar cookie related problem.

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.

So, in this case I would need to recode the last part of the script, assuming I had just created the cookie.



来源:https://stackoverflow.com/questions/22376407/php-undefined-index-when-checking-cookie-value-and-cookie-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!