Cookies in php

A cookie is basically a string that contains several fields. A server can send one or more cookies to a browser in the headers of a response. Some of the cookie’s fields indicate the pages for which the browser should send the cookie as part of the request. The value field of the cookie is the payload—servers can store any data they like there (within limits), such as a unique code identifying the user, preferences, etc.

Use the setcookie() function to send a cookie to the browser:

setcookie(name [, value [, expire [, path [, domain [, secure ]]]]]);

This function creates the cookie string from the given arguments and creates a Cookie header with that string as its value. Because cookies are sent as headers in the response, setcookie() must be called before any of the body of the document is sent. The parameters of setcookie() are:

name

A unique name for a particular cookie. You can have multiple cookies with different names and attributes. The name must not contain whitespace or semicolons.

value

The arbitrary string value attached to this cookie. The original Netscape specification limited the total size of a cookie (including name, expiration date, and other information) to 4 KB, so while there’s no specific limit on the size of a cookie value, it probably can’t be much larger than 3.5 KB.

expire

The expiration date for this cookie. If no expiration date is specified, the browser saves the cookie in memory and not on disk. When the browser exits, the cookie disappears. The expiration date is specified as the number of seconds since midnight, January 1, 1970 (GMT). For example, pass time() + 60 * 60 * 2 to expire the cookie in two hours’ time

path

The browser will return the cookie only for URLs below this path. The default is the directory in which the current page resides. For example, if /store/front/ cart.php sets a cookie and doesn’t specify a path, the cookie will be sent back to the server for all pages whose URL path starts with /store/front/.

domain

The browser will return the cookie only for URLs within this domain. The default is the server hostname.

secure

The browser will transmit the cookie only over https connections. The default is false, meaning that it’s OK to send the cookie over insecure connections.

When a browser sends a cookie back to the server, you can access that cookie through the $_COOKIE array. The key is the cookie name, and the value is the cookie’s value field. For instance, the following code at the top of a page keeps track of the number of times the page has been accessed by this client:

$pageAccesses = $_COOKIE[‘accesses’];
setcookie(‘accesses’, ++$pageAccesses);

When decoding cookies, any periods (.) in a cookie’s name are turned into underscores. For instance, a cookie named tip.top is accessible as $_COOKIE[‘tip_top’].

Leave a Comment