Skip to content
Advertisement

Cookie is not recognised in PHP

I get Notice: Undefined index: i during the first reload of page with cookies

if( (isset($_COOKIE["i"])) && !empty($_COOKIE["i"])   ){
    setcookie("i",$_COOKIE["i"]+1);
    }
else{
    setcookie("i",1);
}

echo $_COOKIE["i"]; //here is the error

but after 2nd reload,it’s OK.

Advertisement

Answer

The solution is to not use the $_COOKIE array, but a variable

<?php

// Use a variable
$cookieValue = 1;

// Check the cookie
if ((isset($_COOKIE["i"])) && !empty($_COOKIE["i"])) {
    $cookieValue = (int)$_COOKIE["i"] + 1;
}

// Push the cookie
setcookie("i", $cookieValue);

// Use the variable
echo $cookieValue;
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement