Saving State with Cookies

The HTTP protocol is stateless. In order to remember that the user has logged in when proceeding to a new page we need to record the state. This might be done by saving a cookie at the browser machine. Browsers like Netscape and IE support cookies, however, users may choose not to accept them and some platforms (e.g. WAP) do not (always) support cookies.

A cookie is introduced to the client by including a Set-Cookie header as part of an HTTP response. The header has the form:
Set-Cookie: NAME=VALUE; expires=DATE;
path=PATH; domain=DOMAIN_NAME; secure
This header can be generated by the PHP-function setcookie (string NAME [, string VALUE [,int EXPIRE [,string PATH [, string DOMAIN_NAME [,int secure]]]]]) as illustrated in the example below.
<?
setcookie ("pass", $pass,time()+600);    /* expires in 10 minutes */
setcookie ("user", $user,time()+600);    /* expires in 10 minutes */
?>
Once the cookies have been set, they can be accessed on the next page load, directly or with the $_COOKIE (PHP 4.1.0) or $HTTP_COOKIE_VARS arrays.

You delete cookies again by calling the function setcookie() with the same name, but without a value. This sets a header with the same name (and path), but an expires time in the past.
<?
setcookie ("pass");
setcookie ("user");
?>

Since cookies are set by headers it is important not to set them before any other data is output. Moreover, cookie headers must be set before any other headers, as e.g. the authentication header.

You can read more about cookies in the specification at Netscape's site.

It is generally not a good idea to store the password and other sensitive data in a cookie.

Instead one should generate a unique session ID, and only store this session ID at the client. At the server one then records which user-specific data is related to this session ID. When the user logs out (or after a certain period of time) this information on the server can be deleted.