Sei sulla pagina 1di 4

PHP Tutorial: Sessions

By Vince Barnes
There is a relationship between Sessions and Cookies -- they serve somewhat the same purpose,
and are, to a certain extent, usable interchangeably. Sessions, which were integrated into PHP in
version 4 of the language, are a means to store and track data for a user while they travel through
a series of pages, or page iterations, on your site.

The most significant differences between the two are that cookies are stored on the client, while the
session data is stored on the server. As a result, sessions are more secure than cookies (no
information is being sent back and forth between the client and the server) and sessions work even
when the user has disabled cookies in their browser. Cookies, on the other hand, can be used to
track information even from one session to another by setting it's time( ) parameter (see
http://www.htmlgoodies.com/php/p14cookies.html)

How Sessions Work

Sessions in PHP are started by using the session_start( ) function. Like the setcookie( ) function,
the session_start( ) function must come before any HTML, including blank lines, on the page. It will
look like this:

<?php
session_start( );
?>
<html>
<head> ....... etc

The session_start( ) function generates a random Session Id and stores it in a cookie on the user's
computer (this is the only session information that is actually stored on the client side.) The default
name for the cookie is PHPSESSID, although this can be changed in the PHP configuration files on
the server (most hosting companies will leave it alone, however.) To reference the session Id in you
PHP code, you would therefore reference the variable $PHPSESSID (it's a cookie name; remember
that from Cookies?)

Your sharp mind may be wondering what happens when you come to the second pass through your
page and reach the session_start( ) function again. PHP knows that there is already a session on
progress and so ignores subsequent instances of the session_start( ) -- phew!!

Using Session Data

Having established a session, you can now create, store and retrieve information pertaining to that
session. You might want, for example, to keep track of items in your visitor's shopping cart.
Information for sessions is stored in a special directory on the server; the path of that directory is
specified in the server's PHP configuration files.

Information to be stored for a session is kept in session variables. Session variables are created by
registering them for the session, using the session_register( ) function. To use that information (on
any page iteration in the session) you simply reference the variable just like you would any other
variable. Here's an example:

<?php
session_start( );
?>
<html>
<head>

<title>Using a session variable</title>

</head>

<body>

<?php

print "Welcome to session number: ";

print $PHPSESSID;

?>

<br />

<?php

session_register("username");

$username = "Goody";

print "Your name is: ";

print $username;

?>

</body>

</html>

In this example we have created a session and displayed the session number. We then registered a
session variable called username (notice the quotes around the variable's name in the call to the
session_register( ) function.)

Next we assigned a value to that variable with the " = " assignment operator (remember operators
from http://www.htmlgoodies.com/php/p05expressions.html?) and then displayed the value of that
session variable.

We now have all the basic tools to establish a session, and to create and use variables that last
through the entire duration of the session.
PHP Tutorial: Saving Sessions in a File

By Vince Barnes
Having created a session and saved session data for use across iterations of pages within a session,
we can see that there would be one more very useful capability. What if we could save session
information from one session to another, returning to information that was saved perhaps a few
days ago? PHP provides this capability by enabling you to save session information in a file.

A particularly useful example of the application of this ability, is to capture and refer to username
and password information. You could, for example, create a login page where a visitor can enter
their user Id (their email address, perhaps) and their password, You would then retrieve session
information from an earlier session, based on their user Id, and present them with customized
views of the rest of your site, based on other stored session variables that you retrieve from the
file. Such a project would, of course, require a little more code that is shown in this tutorial, but
the methods used to save and retrieve the session data are right here!

Another great example of the use of this feature is in conjunction with a shopping cart. Suppose
you have a shopping cart that builds an order as the user makes their selections and stores that
information somewhere based on a unique identifier such as a combination of their user Id and the
session number. Now suppose their connection is interrupted and their session is lost. If you had
saved their original session information in a file, then when they reconnected and logged back into
your site, you would have all the information you would need to retrieve their partially completed
order. That would make for a happy shopper!

And so to the technique, which is simple enough: we're going to use the fopen function to open our
file, the session_encode function to encode our session information into a string, the fputs function
to write it into our file and the fclose function to close the file. Here's an example:

<?php

session_register("username");
session_register("password");
session_register("ordernumber");

$username = "Goody";
$password = "mypass";
$ordernumber = "1234";

$sessionfile = fopen("sessionfile.txt", "w");


fputs($sessionfile, session_encode( ) );
fclose($sessionfile);

?>

As you can see, we are creating three session variables to hold the information we will need and, in
this example, are simply populating those variables from text strings. you will remember from the
file system tutorial in this series about file use of the file functions shown here. You can see here
that in the fputs instruction we are using the session_encode function to take all our session
information (which includes all our session variables, but does not include the session number) and
encode it into a string which becomes the information we write (fputs) to our file.

Now that we have our information safely tucked away, we need a method to retrieve it again when
we need it. For this, we'll use the fgets function to get the record and the session_decode to
retrieve the session information from the record returned. Here we go:
<?php
session_start( );
?>

<html><head> ....... etc.

<?php

$sessionfile = fopen("sessionfile.txt", "r");


session_decode(fputs($sessionfile, 4096) );
fclose($sessionfile);
?>

There are a couple of things to notice here. First, you'll see that we started a new session (with the
session_start coming before anything else, as required - remember that from here?) because we
need to have an active session to be able to create the session_variables, which is what the
session_decode is going to do.

Next you'll notice that the session_encode and session_decode instructions are written the other
way round from each other, with respect to their associated fputs and fgets functions. Think of it
like this: when writing, we want to write the result of the session_encode so the fputs contains the
session_encode; when reading, we want to decode the result of the fgets function, so the
session_decode contains the fgets. (Technically, it may be inaccurate to speak of one "containing"
the other, but it certainly helps to think of it that way!)

Another thing to watch out for is the scope of our variables (remember scope form the functions
tutorial?) In the first example above, we have specific statements to define the session variable, so
their scope may be more obvious, but in the second, the variable will be defined by the
session_decode function and so the scope might not immediately occur to you. In either case, if
the definition of the variable occurs within a function (that is, you have written these instructions
inside some function) the scope of the session_variables will be local to that function. If that's not
what you want, you would have to add the "global" parameter. In the second example above, this
would mean adding a global definition for the variables prior to invoking the session_decode
function, like this:

$sessionfile = fopen("sessionfile.txt", "r");


global $username, $password, $ordernumber;
session_decode(fputs($sessionfile, 4096) );
fclose($sessionfile);

Finally, you might want to think a little about the file name you use. In these examples we used a
file called "sessionfile.txt". It might be more useful to you to name your file something else, such
as the user Id, or a combination such as the user Id and an application identifier (for example,
"vincebarnesorders.txt") so that you will know which file to get your session information from when
the user comes back into your page.

Potrebbero piacerti anche