Introducing Cookies

On the application side, you can use cookies in your PHP scripts to control access to certain areas of your Web site. A cookie is a small amount of data stored by the user's browser in compliance with a request from a server or script. A host can request that up to 20 cookies be stored by a user's browser. Each cookie consists of a name, value, and expiry date, as well as host and path information. An individual cookie is limited to 4KB.

After a cookie is set, only the originating host can read the data, ensuring that the user's privacy is respected. Furthermore, the user can configure her browser to notify her of all cookies set, or even to refuse all cookie requests. For this reason, cookies should be used in moderation and should not be relied on as an essential element of an environment design without first warning the user.

The Anatomy of a Cookie

A PHP script that sets a cookie might send headers that look something like this:

HTTP/1.1 200 OK
Date: Tue, 02 Oct 2001 13:39:58 GMT
Server: Apache/1.3.26 (Unix) PHP/4.2.3
X-Powered-By: PHP/4.2.3
Set-Cookie: vegetable=artichoke; path=/;
Connection: close
Content-Type: text/html

As you can see, this Set-Cookie header contains a name/value pair, path, and domain. The name and value will be URL encoded. Should it be present, an expires field is an instruction to the browser to "forget" the cookie after the given time and date. The path field defines the position on a Web site below which the cookie should be sent back to the server. The domain field determines the Internet domains to which the cookie should be sent. The domain cannot be different from the domain from which the cookie was sent, but can nonetheless specify a degree of flexibility. In the preceding example, the browser will send the cookie to the server and the server

If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. The browser's headers might look something like this:

GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */*
Accept-Encoding: gzip
Accept-Language: en,pdf
Accept-Charset: iso-8859-1,*,utf-8
Cookie: vegetable=artichoke

A PHP script will then have access to the cookie in the environment variable HTTP_COOKIE or as part of the $_COOKIE superglobal:

print "$_SERVER[HTTP_COOKIE]<BR>";     // prints "vegetable=artichoke"
print getenv("HTTP_COOKIE")."<BR>";    // prints "vegetable=artichoke"
print $_COOKIE['vegetable']."<BR>";    // prints "artichoke"

    Part III: Getting Involved with the Code