1

I have an issue. When I want to set Cookie with boolean(just false value) it doesn't store.

setcookie('myCookie',false);

even when I add expire time

setcookie('myCookie',false,time()+3600);

Notice: Undefined index: myCookie in C:\xampp\htdocs\Web\php\php_global_user.php on line 4

2 Answers2

10

Cookies are plain text. When you cast a PHP boolean to text you only get sensible values with true because that's how PHP is designed:

var_dump((string)true, (string)false);
string(1) "1"
string(0) ""

Just use text from the beginning:

setcookie('myCookie', '0');

... or:

setcookie('myCookie', $value ? '1' : '0');
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
3

Use 0 and 1 instead and change it back to boolean again then, when you load the cookie:

// set value to example variable
$setVar = true;

// setting the cookie
setcookie('myCookie', $setVar ? '1' : '0');

// reading the cookie
$readVar = isset($_COOKIE['myCookie']) && $_COOKIE['myCookie'] === '1';
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
Andreas
  • 2,821
  • 25
  • 30