Specifications

Advanced PHP Techniques
P
ART IV
430
This chapter will discuss the session control functionality in PHP 4.
We will cover
What session control is
Cookies
Setting up a session
Session variables
Sessions and authentication
What Session Control Is
You might have heard it said that HTTP is a stateless protocol.What this means is that the
protocol has no built-in way of maintaining state between two transactions. When a user
requests one page, followed by another, HTTP does not provide a way for us to tell that both
requests came from the same user.
The idea of session control is to be able to track a user during a single session on a Web site.
If we can do this, we can easily support logging in a user and showing content according to her
authorization level or personal preferences. We can track the users behavior. We can imple-
ment shopping carts.
In earlier versions of PHP, session control was supported via PHPLib, the PHP Base Library,
which is still a useful toolkit. You can read about it at
http://phplib.netuse.de/index.php3
As of version 4, PHP includes native session control functions. They are conceptually similar
to PHPLib, but PHPLib offers some extra functionality. If you find that the native functions do
not quite meet your needs, you might want to take a look at it.
Basic Session Functionality
Sessions in PHP are driven by a unique session ID, a cryptographically random number. This
session ID is generated by PHP and stored on the client side for the lifetime of a session. It can
be either stored on a users computer in a cookie, or passed along through URLs.
The session ID acts as a key that allows you to register particular variables as so-called session
variables. The contents of these variables are stored at the server. The session ID is the only
information visible at the client side. If, at the time of a particular connection to your site, the
session ID is visible either through a cookie or the URL, you can access the session variables
stored on the server for that session. By default, the session variables are stored in flat files on
25 7842 CH20 3/6/01 3:42 PM Page 430