简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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