Specifications
the server. (You can change this to use a database if you are willing to write your own
function—more on this in the section “Configuring Session Control.”)
You have probably used Web sites that store a session ID in the URL. If there’s a string of
random looking data in your URL, it is likely to be some form of session control.
Cookies are a different solution to the problem of preserving state across a number of transac-
tions while still having a clean looking URL.
What Is a Cookie?
A cookie is a small piece of information that scripts can store on a client-side machine. You
can set a cookie on a user’s machine by sending an HTTP header containing data in the fol-
lowing format:
Set-Cookie: NAME=VALUE; [expires=DATE;] [path=PATH;]
[domain=DOMAIN_NAME;] [secure]
This will create a cookie called NAME with the value VALUE. The other parameters are all
optional. The expires field sets a date beyond which the cookie is no longer relevant. (Note
that if no expiry date is set, the cookie is effectively permanent unless manually deleted by you
or the user.) Together, the path and domain can be used to specify the URL or URLs for which
the cookie is relevant. The secure keyword means that the cookie will not be sent over a plain
HTTP connection.
When a browser connects to an URL, it first searches the cookies stored locally. If any of them
are relevant to the URL being connected to, they will be transmitted back to the server.
Setting Cookies from PHP
You can manually set cookies in PHP using the setcookie() function. It has the following
prototype:
int setcookie (string name [, string value [, int expire [, string path
[, string domain [, int secure]]]]])
The parameters correspond exactly to the ones in the Set-Cookie header mentioned previously.
If you set a cookie as
setcookie (“mycookie”, “value”);
when the user visits the next page in your site (or reloads the current page), you will have
access to a variable called $mycookie containing the value “value”. You can also access it via
$HTTP_COOKIE_VARS[“mycookie”].
Using Session Control in PHP
C
HAPTER 20
20
USING SESSION
C
ONTROL IN
PHP
431
25 7842 CH20 3/6/01 3:42 PM Page 431










