8

Is there any difference between setting a cookie via setcookie() and $_COOKIE ?

Sometimes,when setting a cookie via setcookie,i don't get the value of that cookie via $_COOKIE['cookie_name'].But js console.log immediately after setcookie,shows that cookie is set but if i try to get the value of the cookie via $_COOKIE,i don't get the updated value.

I'm confused..!!

Mike Purcell
  • 19,847
  • 10
  • 52
  • 89
Mayur Buragohain
  • 1,566
  • 1
  • 22
  • 42

4 Answers4

14

You can't actually "set" a cookie with some code like this:

$_COOKIE['cookie'] = $my_var;

All this does is add a new value to the $_COOKIE array. No Set-Cookie HTTP header is sent back to the client (browser) in the response and no cookie will be created on the client.

Use the setcookie() function to set cookies.

The current accepted answer correctly points out that $_COOKIE is set/initialized at the start of the PHP process and isn't updated after that. You can update it yourself but don't expect that value to stick on the next request.

Scott Jungwirth
  • 6,105
  • 3
  • 38
  • 35
3

In setcookie function you can only set the cookie name. If you want to get that cookie value then you can take it via the $_COOKIE['name']

Be sure that when you create cookie you need to set domain name in setcookie function as well.

Nikul
  • 1,025
  • 1
  • 13
  • 33
1

In PHP, we can set a cookie with the function setcookie(). The syntax of the function is

setcookie(name,value,expire,path,domain,secure)

For example, setcookie('name',$name,0,'/'); will create a cookie named name with value of the variable $name in the root directory '/'. Inorder to access the cookie, we can use $_COOKIE['cookiename'];

Jenz
  • 8,280
  • 7
  • 44
  • 77
  • i am aware of setcookie syntax and as i said,a console.log after setting cookie via setcookie gives correct result but i can't obtain the updated cookie value via $_COOKIE[cookie_name] . Thats why the question. – Mayur Buragohain Nov 19 '13 at 06:56
  • where you are setting the cookie? In the root? – Jenz Nov 19 '13 at 06:58
  • `setcookie("candidate_id", $new_candidate_id, time()+3600);` using this to set cookie. Using `echo "";` to console output and after that `if(isset($_COOKIE['candidate_id'])){ echo "from cookie".$_COOKIE['candidate_id'];}` – Mayur Buragohain Nov 19 '13 at 07:14
  • although console.log outputs correct value but echo $_COOKIE['candidate'] gives an old value if the cookie was already set earlier. – Mayur Buragohain Nov 19 '13 at 07:15
  • 1
    here, you are not setting the path of the cookie. Try with setcookie("candidate_id", $new_candidate_id, time()+3600,'/'); – Jenz Nov 19 '13 at 07:18
1

With setcookie you can only set cookie in php :

setcookie("myCookie", $value, time() + 3600);

But if you want to get or use that cookie you can use $_COOKIE, like if you want to get some cookie value use: echo $_COOKIE['cookie_name'];