3

I am using this code

setcookie("we", 2, time()+3600*24*365);
echo "'".$_COOKIE["we"]."'";

to set a cookie for my site.

This works fine on localhost and I get '2' however when I run this on my online site I get ''. Why is this happening?

UPDATE I am trying this code to test my cookie problem

$c = "cookiesfwefwfwef";
if(isset($_COOKIE[$c])){
    echo "The cookie '".$c."' is going to be destroyed";
    setcookie($c, 23,  time()-3600*24*365, $site_url);
}else{
    echo "The cookie '".$c."' is going to be set";
    setcookie($c, 23,  time()+3600*24*365, $site_url);
}

The problem is that every time I refresh my browser on my online site I keep getting The cookie 'cookiesfwefwfwef' is going to be set, however when I refresh my browser on my localhsot site I get The cookie 'cookiesfwefwfwef' is going to be set then The cookie 'cookiesfwefwfwef' is going to be destroyed then The cookie 'cookiesfwefwfwef' is going to be setand so on.

Am I doing something wrong?

Cœur
  • 34,719
  • 24
  • 185
  • 251
Jack Hill
  • 39
  • 3

2 Answers2

1

setcookie() will set COOKIE on browser side after your server sends response to browser. So you can not user $_COOKIE within same request.

After setcookie, when browser sends request again at that time you will get value of $_COOKIE.

If you want to use $_COOKIE within same request, then kindly assign value to it like this: $_COOKIE["we"] = 2;

Parixit
  • 3,739
  • 3
  • 38
  • 59
0

cookie value will be printed on the next page refresh also you haven't specified the cookie path.

setcookie("we", 2, strtotime("+1 year"), "/");
echo "'".$_COOKIE["we"]."'";
Red Acid
  • 227
  • 1
  • 3
  • 14