Developer

10 tips for PHP scripts: Using native sessions

You can use sessions to maintain user-specific veriables without setting multiple cookies. Learn to use native sessions.

By Julie Meloni
(2/6/01)

One of the more long-awaited features of PHP 4.0 was its session support. Users of PHP 3.0 had to use a third-party library or nothing at all, and the lack of session support was one of PHP's biggest detractions. No more, though, as session support has been part of PHP 4.0 since the early beta releases.

You can use sessions to maintain user-specific variables throughout a user's stay at your Web site without setting multiple cookies, using hidden form fields, or storing information in a database to which you'd probably have to connect way too often.

Starting a session on a page tells the PHP engine that you want to either start a session (if one isn't already started) or continue a current session:

session_start();

Starting a session will send an identification string (such as 940f8b05a40d5119c030c9c7745aead9) to the user via a cookie; on the server side, a matching temporary file is created with the same name, such as sess_940f8b05a40d5119c030c9c7745aead9. This file contains the registered session variables and their values.

The most common example used to show sessions in action is an access counter:

Start your PHP block, and be absolutely sure that the PHP code is the first line of your file: no white space, no HTML output, nothing. As session functions send a header; if you send white space or HTML output before the session_start() call, you'll get an error.

<?
// if a session does not yet exist for this user, start one
session_start();

Next, register a variable called count.

session_register('count');

Registering a session variable tells PHP that for as long as this session exists, a variable called count also exists. Currently, the variable has no value. However, if you increment it, it will have a value of 1:

$count++;

Put this all together, and you'll have started a session if one wasn't already started, assigned a session id to a user if one doesn't exist, registered the variable called count, and incremented $count by one to represent the initial time the user has accessed the page:

To show users how many times they've accessed this page in their current session, just print the value of $count:

echo "<P>You've been here $count times.</p>";

The entire access count code looks like this:

<?
session_start();
session_register('count');
$count++;
echo "<P>You've been here $count times.</p>";
?>

If you reload the script, you can watch the count increment. Very exciting.

You can register arrays in sessions as well. Suppose you have an array called $faves:

$faves = array ('chocolate','coffee','beer','linux');

You can register this array just like any single variable:

session_register('faves');

You reference the array like any single variable, as well: $faves. If your user indicates his or her favorite things in life on one page of your Web site, and you register those things in a session variable called $faves, then on another page, you can simply print those values out:

<?
session_start();
echo "My user likes:
<ul>";

while (list(,$v) = each ($faves)) {
echo "<li>$v"; }

echo "</ul>";
?>

There you have it: a nice bullet list of your user's favorite things.

Session variables cannot be overwritten by a query string, meaning that you can't type http:///www.yourdomain.com/yourscript.php?count=56 and assign a new value to the registered session variable called $count. This is an extremely important concept for security: you can modify or delete (unregister) session variables on only the server side, within your scripts.

If you want to completely delete a session variable, you unregister it from the system:

session_unregister('count');

To delete a session in its entirety, as from a Logout button, the script would be simple:

session_destroy();

Using sessions to store values alleviates database connectivity overhead as well as messy coding nightmares and long privacy statements about why you're sending fifty cookies to the user throughout his or her visit to your site. One cookie, one value, one big ethereal blob holding everything else: It can't get much simpler than that!

Julie Meloni is the technical director at i2i Interactive and is an avowed proponent of Linux and the open source community. A regular contribtor to CNET Builder.com, she has written a few books on PHP and other technologies.

Editor's Picks