readJohn
readJohn

Reputation: 173

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.

Upvotes: 0

Views: 52

Answers (2)

Chris Haas
Chris Haas

Reputation: 55427

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;

Upvotes: 2

ShadeBob
ShadeBob

Reputation: 74

else{
    setcookie("i",1);
    header("Refresh:0");
}

Upvotes: 0

Related Questions