Native Sessions in PHP

A session can be defined as a series of related interactions between a single client and the Web server, which take place over an extended period of time. This could be a series of transactions that a user makes while updating his stock portfolio, or the set of requests that are made to check an e-mail account through a browser-based e-mail service. The session may consist of multiple requests to the same script, or of requests to a variety of different resources on the same Web site.

Particularly when you want to work with sensitive (or bulky) information, it makes a lot of sense to submit it once and have it stored on the server. Rather than storing the actual data on the client machine, and have to pass it back and forth between the server and client each time, it's far more practical to keep the data on the server, but give the client a "key" to allow it to uniquely identify itself, and consequently any server-side data associated with it. This key is called a session identifier; it uniquely associates a client with a session, and therefore with its data. In PHP, the session identifier is known as the SID (Session ID). SID is a special variable that's specified as a reference number for any particular session.

You saw how to establish a session of sorts when you used cookies to make data persist on the client machine. As noted at the time, though, that isn't a terribly secure way to manage sessions. Fortunately, PHP comes with its own session management system built in, so you don't need to worry too much about the precise implementation details. PHP creates its SID whenever you use the session_start() function, and also by default if you use certain other session-related functions, such as session_register(). The value of the SID is kept in a global variable named PHPSESSID.

You can think of the SID as being like the reference number on an electric bill: you're given the number, the electric company files your details under that number, and presto! You no longer have to give the company all your details every time you call up to complain about its outrageous charges. The SID is automatically created and passed back and forth for you, each time the user clicks a link or submits form.

When you start a PHP session, the server assigns it a session ID, or SID. Any variables that you register as session variables (you'll see how to do this in a moment) are then stored on the server in a cookie-like file. The name of this file is generally the same as the value of the SID. All the client has to do to access this data is to include the SID in its request to the server. It can use a hidden form field, a query string, a cookie, anything at all, as long as the SID makes it into the HTTP request. The server looks up the appropriate session data and makes it available for use in whatever script it then executes.

If you have cookie support enabled, even this is taken care of, because the session manager automatically sends the client a cookie for the SID value. If you can't (or don't want to) use cookies, the simplest thing to do is to add the SID as a term in all query strings that point back to your Web site.

PHP sessions handle this all very neatly; they're an excellent way to learn how to build interactive sites quickly because they completely free you up from worrying about the nitty-gritty details of implementing persistence, and let you get on with the business of building your site. One particularly nice aspect is the knowledge that you have literally thousands of coders scrutinizing your persistence mechanism (because it's a part of PHP itself!) and ensuring that the underlying code works as well as possible. What's more, sessions are very well documented in the core PHP documentation, available at the official PHP Web site (www.php.net/). So, sessions are easy, reliable, and almost universally available; but how exactly do you use them?

In most cases, using PHP sessions is as simple as telling PHP, "I want variables X, Y, and Z to remain persistent," and letting PHP do the work. All that you, the coder, need to worry about is how to tell PHP to register a session variable—that is, make a given variable persistent—and then how to access those variables.

The function for registering a persistent variable for use with PHP sessions is session_register(). Given the name (without the dollar sign) of a variable, it makes that variable and its contents persist for the duration of the current session. If there isn't currently a session defined, a new one is created automatically. The length of the session (how long the session remains intact without the user having to use the site) is determined by the session timeout setting in the php.ini file. The default is 1,440 seconds (24 minutes).

If you wanted to maintain persistent variables called myvar1 and myvar2, for example, here's how you'd begin your PHP script:

<?php
session-register("myvar1");
session-register("myvar2");
?>

You must put this code at the top of the script. Behind the scenes, you're using cookies. Again, to not mess with HTTP headers, you must be sure to register all the session variables before any HTML headers are sent out. It's good practice to do so at the very top of a script, in a self-contained snippet of PHP, as shown.

Once you've registered a variable, retrieving its contents is ridiculously simple—just access the session variable as if it were any other global variable! If you used the preceding code to register variables $myvar1 and $myvar2, you can use them just like any other variables. The only difference is that they persist for as long as the session lasts, so that the next time the page is called within the session, by the same user, the variables will contain the same values they had when the page finished executing the last time.

To use PHP sessions with Windows, you may need to modify the variable session.save_path in your php.ini file so that it refers to a valid Windows directory (D:\WinNT\Temp, for example, where D is the letter for your hard drive).

Try It Out: Count Page Accesses

Start Example:

Ready for some more code? This time you'll count the number of times a user has accessed pages on a Web site since the start of the current session. This task is easily accomplished using PHP sessions, with various counters (one for each page on the site) made persistent by registering them with session_register(). Here's the code

<?php>
session_register('view1count');
session_register('view2count');
session_register('view3count');
session_register('view4count');
?>
<?php>

//The rest of the script illustrates how to make hyperlinks that hand PHP
what it needs to access your session data - namely, STD.
echo "<html><head><title>Web Page Hit Counter</title></head><body>';
if (isset($_GET['whichpage'])) {
   echo "<b>You are currently on page $_GET[whichpage].</b><br><br>\n";
  $_SESSION["view".$_GET['Whichpage']."count"]++;
}

for ($i=1; $ <= 4; $i++) {
   if (isset (S_GET['whichpage']) == $i) {
      echo "<b><a href=\"sessions.php?".session_id()."&whichpage=$i\">Page
$i</a></b>
   } else {
      echo "<a href=\"sessions.php?".session_id()."whichpage=$i\">Page $i</a>;
   }
   echo ", which you have chosen ".$_SESSION["view".$i."count"]."times.<BR>\n";
}
echo "\n\n<br><br>\n\n";
echo "</body></html>";
?>

Save this file as sessions.php. Run it and change pages a few times.

Now visit a bunch of other pages and then run the script again. You'll find that these numbers have persisted. Only when you shut down the browser will the session end.

How it Works

This simple program starts by using session_register() to register four session variables. They are placed in a separate block of PHP code (starting with <?php and ending with ?>) to make it clear that they sit before anything else, and don't fall foul of any HTML headers:

<?php
session_register('view1count');
session_register('view2count');
session_register('view3count');
session_register('view4count');
?>

An HTML header is echoed out, and $_GET['whichpage'] (denoting which page you're currently on) is tested to see if it's defined. If it is, its value is used to display an appropriate message and determine which page's view count variable you need to increment:

if (isset($_GET['whichpage'])) {
   echo "<b>You are currently on page $_GET[whichpage].</b><br><br>\n" ;
  $_SESSION["view".$_GET['whichpage']."count"]++;
}

A for loop begins cycling through each of the four pages you want to use. You display a link for each, along with a message that tells the user how many times that page has been visited during the current session. The link to the current page is displayed in bold type:

for ($i = 1; $i <= 4; $i++) {
   if (isset($_GET['whichpage']) == $i) {
      echo "<b><a href=\"sessions.php?".session_id()."&whichpage=$i\">Page
$i</a></b>";
   } else {
      echo "<a href=\"sessions.php?".session_id()."&whichpage=$i\">Page $i</a>";
   }
   echo ", which you have chosen ".$_SESSION["view".$i."count "]." times.<BR>\n";
}
echo "\n\n<br><br>\n\n";
echo "</body></html>" ;
?>

Each of the links specifies three things: the current script (specified by sessions.php), the current session (identified by session_id()), and the page to which you want to link (that's what $_GET['whichpage'] is for). And that's it. All the session handling code you had to worry about was there in the first four lines. It could hardly be simpler!