Posts Tagged ‘cookie’

Reading Cookie Values

Wednesday, March 12th, 2008

Problem
You want to read the value of a cookie that’s been previously set.
Solution
Look in the $_COOKIE superglobal array:

if (isset($_COOKIE['flavor'])) {
print "You ate a $_COOKIE[flavor] cookie.";
}

Discussion
A cookie’s value isn’t available in $_COOKIE during the request in which the cookie is
set. In other words,the setcookie() function doesn’t alter the value of $_COOKIE. On
subsequent requests,however,each cookie is stored in $_COOKIE. If register_globals
is on, cookie values are also assigned to global variables.
When a browser sends a cookie back to the server,it sends only the value. You can’t
access the cookie’s domain,path,expiration time,or secure status through $_COOKIE
because the browser doesn’t send that to the server.
To print the names and values of all cookies sent in a particular request,loop
through the $_COOKIE array:

foreach ($_COOKIE as $cookie_name => $cookie_value) {
print "$cookie_name = $cookie_value<br>";
}

Setting Cookies

Tuesday, March 11th, 2008

Problem
You want to set a cookie.
Solution
Use setcookie():

setcookie('flavor','chocolate chip');

Discussion
Cookies are sent with the HTTP headers,so setcookie() must be called before any
output is generated. You can pass additional arguments to setcookie() to control cookie behavior. The
third argument to setcookie() is an expiration time,expressed as an epoch timestamp.
(more…)