0

I am having problem with setting up a php cookie, what am I doing wrong? Below I added 3 examples which I tried. Next to the examples, I also tried to change the time which the cookie is working but is all did not work.

Evert time I get the notworking variable indicating that the cookie is not set, do you know what am I doing wrong? Thanks!

Example from: http://www.w3schools.com/php/showphp.asp?filename=demo_func_http_setcookie

$works="It is working!";
$notworking="Not working";
$name=20;
setcookie($name_cookie, $name, time() + 100000, '/');

if (isset($_COOKIE[$name_cookie])){
echo $works;

}
else{
    echo $notworking;
}

Example from:
http://php.net/manual/en/function.setcookie.php And Query about PHP cookie

Example 2:

$works="It is working!";
$notworking="Not working";
$name=20;
setcookie("name_cookie", "name", time() + 100000, '/');

if (isset($_COOKIE["name_cookie"])){
echo $works;
echo $_COOKIE[$name_cookie];
echo $name_cookie;
}
else{
    echo $notworking;
}

Example 3

$works="It is working!";
$notworking="Not working";
$name=20;
setcookie("name_cookie", $name, time() + 100000, '/');
if (isset($_COOKIE["name_cookie"])){
echo $works;
}
else{
    echo $notworking;
}
Community
  • 1
  • 1
TimothyUtrech
  • 77
  • 1
  • 6

2 Answers2

0

You're setting it correctly.

This is the expected behavior. Cookie is set on server and sent to the client. After the next page refresh, the cookie data is available through $_COOKIE.

BudwiseЯ
  • 1,846
  • 2
  • 16
  • 28
0

Whenever you set a cookie, it becomes available in next page load, You can't access it right after creating it.

sharafatalee
  • 134
  • 3