Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between setcookie and $_COOKIE in php

Tags:

php

cookies

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..!!

like image 730
Mayur Buragohain Avatar asked Nov 19 '13 06:11

Mayur Buragohain


People also ask

What is $_ cookie in PHP?

Introduction. The superglobal $_COOKIE stores variables passed to current script along with HTTP request in the form of cookies. $HTTP_COOKIE_VARS also contains the same information, but is not a superglobal, and now been deprecated.

What are cookies identify and explain Setcookie () with an example?

The setcookie() function defines a cookie to be sent along with the rest of the HTTP headers. A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too.

How many types of cookies are there in PHP?

There are two types of cookies, they are: Session Cookie: This type of cookies are temporary and are expire as soon as the session ends or the browser is closed. Persistent Cookie: To make a cookie persistent we must provide it with an expiration time.

Where Setcookie function must appear in PHP?

Cookies must be sent before any HTML is sent to the page or they do not work, so the setcookie() function must appear before the <html> tag.


1 Answers

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.

like image 91
Scott Jungwirth Avatar answered Sep 19 '22 00:09

Scott Jungwirth