Patience PaysNow that you've used PHP with MySQL and SQLite, you probably think you know everything you need to get started with PHP programming. In fact, you might even be thinking of cutting down your visits to Zend.com altogether, giving up this series for something flashier and cooler... Uh-uh. Big mistake. You see, while built-in database support makes programming with PHP easy, it isn't the only thing that makes PHP so popular. An easy-to-use XML API and new exception handling mechanism (in PHP 5), support for pluggable modules, and built-in session management are just some of the many other features that make PHP rock. And all these capabilities are going to be explored, in depth, right here in this very series, if you can just find it in yourself to hang around a little longer. So close your eyes, take a deep breath, and read on to find out all about this tutorial's topic: sessions and cookies. Party TimeMaybe you heard this at the last party you went to: "HTTP is a stateless protocol, and the Internet is a stateless development environment". No? Hmmm. Obviously, you don't go to the right parties. In simple language, all this means is that HTTP, the HyperText Transfer Protocol that is the backbone of the Web, is unable to retain a memory of the identity of each client that connects to a Web site, and therefore treats each request for a Web page as a unique and independent connection, with no relationship whatsoever to the connections that preceded it. This "stateless environment" works great so long as you're aimlessly surfing the Web, but it can cause a serious headache for sites that actually depend on the data accumulated in previous requests. The most common example is that of an online shopping cart - in a stateless environment, it becomes difficult to keep track of all the items you've shortlisted for purchase as you jump from one catalog page to another. Obviously, then, what is required is a method that makes it possible to "maintain state", allowing client connections to be tracked and connection-specific data to be maintained. And thus came about cookies, which allow Web sites to store client-specific information on the client system, and access the information whenever required. A cookie is simply a file, containing a series of variable-value pairs and linked to a domain. When a client requests a particular domain, the values in the cookie file are read and imported into the server environment, where a developer can read, modify and use them for different purposes. A cookie is a convenient way to carry forward data from one client visit to the next. Another common approach is to use a session to store connection-specific data; this session data is preserved on the server for the duration of the visit, and is destroyed on its conclusion. Sessions work by associating every session with a session ID (a unique identifier for the session) that is automatically generated by PHP. This session ID is stored in two places: on the client using a temporary cookie, and on the server in a flat file or a database. By using the session ID to put a name to every request received, a developer can identify which client initiated which request, and track and maintain client-specific information in session variables (variable-value pairs which remain alive for the duration of the session and which can store textual or numeric information). Sessions and cookies thus provide an elegant way to bypass the stateless nature of the HTTP protocol, and are used on many of today's largest sites to track and maintain information for personal and commercial transactions. Typically, you use a session to store values that are required over the course of a single visit, and a cookie to store more persistent data that is used over multiple visits. PHP has included support for cookies since PHP 3.0, and built-in session management since PHP 4.0. Both these features are enabled by default, so you don't have to do anything special to activate them. Instead, scroll down and take a look at your first session. The First SessionOne of the standard examples used to demonstrate how a session works is the hit counter application. This is a simple counter that initializes a variable the first time you visit a Web page, and increments it each time you reload the page. The counter variable is stored in a session, which means that if you browse to another site and then return, the last saved value of the counter will be restored (so long as you didn't destroy the session by shutting down the browser in the interim). Take a look at the code:
To see how this works, request the script above through your browser a few times. You will notice that the counter increases by 1 on each subsequent page load. If you open up two browser windows and request the same page in each one, PHP will maintain and increment individual session counters for each browser instance. The session ID is used to identify which client made which request, and recreate the prior saved environment for each individual session. This also means that if you visit one (or more) other Web sites during the same session and then return to the script above without shutting down your browser in the interim, your previous session will be retrieved and recreated for you.
Every session in PHP begins with a call to the
If the example above doesn't work as advertised, check to make sure that the
Remember MeHere's another example, this one asking you to log in and then storing your login name and session start time as two session variables. This information is then used to display the total number of minutes the session has been active.
In this example, the presence or absence of a session variable is used to decide which
of the three possible screens to display. The session start time is also recorded in
It's important to note that the call to Warning: Cannot send session cache limiter - headers already sent (output started at ...)
it's usually because somewhere, somehow, some output has found its way to the browser before
As noted previously, every session has a unique session ID, which PHP uses to keep track of
different clients. This session ID is a long alphanumeric string, which is automatically
passed by PHP from page to page so that the continuity of the session is maintained. To see
what it looks like, use the
When the user shuts down the client browser and destroys the session, the
In case you were wondering if you read that right - yes, before you can call
Remember that
You can read more about sessions and session handling functions at http://www.php.net/manual/en/ref.session.php. Rules Of The GameA session works by using an in-memory cookie, which explains why it's only active while the browser instance that created it is active; once the browser instance is terminated, the memory allocated to that instance is flushed and returned to the system, destroying the session cookie in the process. If you want longer-lasting cookies, you can use PHP's built-in cookie functions to write data to the user's disk as a cookie file, and read this data back as and when needed. Before you start using cookies, there are a few things you should be aware of:
More information on cookies can be obtained from Netscape, the people who originally invented them. Visit http://www.netscape.com/newsref/std/cookie_spec.html for the Netscape cookie specification. It's important to remember that, since cookies are stored on the user's hard drive, you as the developer have very little control over them. If a user decides to turn off cookie support in his or her browser, your cookies will simply not be saved. Therefore, avoid writing code that depends heavily on cookies; and have a backup plan ready in case cookie data cannot be retrieved from the client. With that caveat out of the way, let's look at some simple cookie-handling code in PHP. Meeting Old Friends
PHP offers a single function for cookie manipulation:
To see how this works, request the page above through your browser a couple of times. The first time around, because no cookie has yet been set, the first message will be displayed. On all subsequent attempts, because the cookie has already been set, the client will be recognized and the second message will be displayed. Note that this works even if you terminate the browser instance, restart it and visit the page again - a marked difference from what happened in the session examples you saw earlier.
The
Cookie values are automatically sent to PHP from the client, and converted to key-value
pairs in the Warning: Cannot add header information - headers already sent by (output started at ... ) Form And FunctionHere's another, slightly more complex example:
In this case, the value entered into the form is stored as a cookie called email, and automatically retrieved to pre-fill the form field on all subsequent requests. This technique is frequently used by Web sites that require the user to enter a login name and password; by automatically pre-filling the username field in the login box with the value used in the last successful attempt, they save the user a few keystrokes.
This example also demonstrates how you can set more than one cookie for a domain, by
calling
To remove a cookie from the client, simply call
Read more about cookies and the Access GrantedAs I said at the beginning of this tutorial, cookies and sessions are two different ways of making data "persistent" on the client. A session retains data for the duration of the session, while a cookie retains values for as long as you need it to. With that in mind, let's now look at an example that uses them both. The application here is a simple user authentication system, where certain pages can only be viewed by users who successfully log in to the system. Users who have not been authenticated with a valid password are denied access to these "special" pages. The list of valid usernames and passwords is stored in a MySQL database, and PHP is used to verify a user's credentials and decide whether or not to grant access. Assuming the MySQL database table looks like this +-------+-----------------------------------------------+
with a unique username field and a password field created with the
Here, the values entered into the login box are integrated into a MySQL SELECT query, which is executed on the user table. If both username and password match, a single record will be returned, indicating that authentication succeeded; if they don't, no records will be returned, indicating that authentication failed.
Assuming authentication succeeds, a session is initialized, the Of course, this isn't enough by itself. While the script above performs authentication and initializes both a session and a cookie if the user's credentials are validated, a security check must also be carried out on each of the restricted pages. Without this check, any user could bypass the login screen and simply type in the exact URL to each page to view it.
Since it is clear from the previous script that the session variable
Pretty neat, huh? Only authenticated users will be able to see this page, because only
their clients will have a session with the That's about it for this tutorial. In Part Eleven, I'll be telling you all about SimpleXML, the new XML processing toolkit that comes bundled with PHP 5. Make sure you come back for that! |