Articles: 843 | Categories: 148   
   
   
Home Articles Contact Us
 
 
 
 
Introduction to PHP Sessions (0 Comments)
Admin: Posted Date: March 3, 2010

This article is an step-by-step introduction to using sessions in PHP. It features fundamentals tips and actual examples to show you what you should and shouldnt do with sessions.

An Introduction To PHP Sessions

Introduction

This article is an introduction to using sessions in PHP, including:

  1. What is a session?
  2. How do I use a Session?
  3. How do sessions work?
  4. How do I change the value of a session variable?
  5. Can I destroy a session variable?
  6. What should I do to destroy a whole session?
  7. Can I store an array in a session?
  8. Can I store an object in a session?
  9. Can I store an file pointer in a session?
  10. How are sessions stored?
  11. When do sessions expire?
  12. How can I send headers then start a session?
  13. Session security

What is a Session?

A session is basically a way of storing variables and making them available across multiple pages on your web site. This can be very useful as the user does not ever need to see what is going on behind the scenes. Nor do we need to fill the URL with mind boggling long strings like http://example.com/file.php?id=6&item=pet&type=cat&color=black&eyes=1&temperament=aloof&var=etc.

Also the need for the user to post a form is not required, so all interaction is hidden from the user.

How Do I Use a Session?

Here we will demonstrate a session in its simplest form, that is, setting a session variable on a web page and recalling the value of it on a second page. We will begin by creating a session variable called foo and we shall assign the value of bar to it. A session variable looks like this: $_SESSION['variable']

We use the PHP super global $_SESSION to hold it. More on this later. Our first page we will call page1.php and the code will look as follows.

Listing 1 page1.php
<?php
// begin the session
session_start();
// set the value of the session variable 'foo'
$_SESSION['foo']='bar';
// echo a little message to say it is done
echo 'Setting value of foo';
?>

With that done, we can create page2.php, which will start a session, then it will echo the value of the session variable foo.

Listing 2 page2.php
<?php
// begin our session
session_start();
// echo the session variable
echo 'The value of foo is '.$_SESSION['foo'];
?>

Try the above example, we will build on it as we go and discover new things to do with sessions, but first, let’s look at what happened here. On page2.php we again used session_start(). You must use this on every page you wish to use sessions. In most cases, it will be the first line of code on the page that does anything, following PHP that a session is happening and to load up the session variables, if a session is not already active, PHP will begin a new session upon adding a new variable to $_SESSION.

You cannot send ANYTHING to the browser before session_start().

This means no text, not even a newline or a space. There is a method of doing this but more of that later. Let’s change our page2.php to echo some text before we use session_start().

Listing 3 page2.php
<?php
// output some text to the browser before starting the session
echo 'This is a bad thing to do';
// begin our session
session_start();
// echo the session variable
echo 'The value of foo is '.$_SESSION['foo'];
?>

When you access page2.php with the above code, it will give you an error that looks something like this:

Listing 4 The warning caused by calling session_start() after output has already commenced (listing-4.txt)
Warning: session_start() [function.session-start]: 
Cannot send session cookie - headers already sent by (output started at /html/page2.php:4) in /html/page2.php on line 7
Warning: session_start() [function.session-start]:
Cannot send session cache limiter - headers already sent (output started at /html/page2.php:4) in /html/page2.php on line 7
The value of foo is

As you can see, when the script reaches the session_start() on line 7, it gives an error. This is because session_start() sends headers to the browser, as does sending text. These headers may only be sent once.

How Do Sessions Work?

Sessions can be used in two ways. The first is cookie based, and the second is url based.

Most sessions are cookie based. What this means is that when a session is started, a cookie is set on the clients machine with a unique session ID or SID. The session variables are stored typically on a file on the server that matches the unique session ID. When a variable is required, the client or browser looks for the file matching the session ID and retrieves the corresponding variables from it. A typical session file stored in the default session file directory would look like this:

sess_fd51ab4d1820aa6ea27a01d439fe9959

Using our example session from above, this file would contain our session information in an array. An array of 1 is a little lacking for our purposes so let’s create several session variables. To demonstrate this let’s make a new page1.php with the following code…

Listing 5 page1.php
<?php
// begin the session
session_start();
// set the value of the session variable 'foo'
$_SESSION['foo']='bar';
// set the value of the session variable 'bar'
$_SESSION['bar']='foo';
// set the value of the session variable 'foobar'
$_SESSION['foobar']='fubar';
// echo a little message to say it is done
echo 'Setting session values';
?>

With this, the session variables foo, bar, and foobar have been stored in the $_SESSION array.

To access them we use the global variable $_SESSION and the array key of the variable we require. To view all the session variables, we can use the following code in our page2.php file.

Listing 6 page2.php
<?php
// begin the session
session_start();
// loop through the session array with foreach
foreach($_SESSION as $key=>$value)
{
// and print out the values
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
}
?>

The output of page2.php should look like this:

Listing 7 Browser output from page2.php (listing-7.txt)
The value of $_SESSION['foo'] is 'bar'
The value of $_SESSION['bar'] is 'foo'
The value of $_SESSION['foobar'] is 'fubar'

As you can see above, when we loop throught the $_SESSION array, the value are displayed. The actual file that stores the session looks like this:

Listing 8 Session data as stored on the filesystem (listing-8.txt)
|s:3:"bar";bar|s:3:"foo";foobar|s:5:"fubar";

How Do I Change The Value Of A Session Variable?

This is easily achieved by simply declaring the variable again like so. If page1.php sets the value of $_SESSION['foo'] to bar, the value can be changed by resetting it like:

Listing 9 page1.php
<?php
$_SESSION['foo'] = 'newbar';
?>

It really is that simple.

What Should I Do To Destroy A Whole Session?

This is often used to log out of applications that store the login information in a session. You can use the code below to destroy your session completely.

Listing 10 listing-10.php
<?php
// Begin the session
session_start();
// Unset all of the session variables.
session_unset();

Can I Store An Array In A Session?

Sure, this is simply done in the same way as setting regular variables.

Let’s create a new page1.php with the following code:

Listing 11 page1.php
<?php
// begin the session
session_start();
// create an array
$my_array=array('cat', 'dog', 'mouse', 'bird', 'crocodile', 'wombat', 'koala', 'kangaroo');
// put the array in a session variable
$_SESSION['animals']=$my_array;
// a little message to say we have done it
echo 'Putting array into a session variable';
?>

Now that we have the array $my_array in a session variable called $_SESSION['animals'] we can have a look through the array as we choose. Use this snippet to create a new page2.php file:

Listing 12 page2.php
<?php
// begin the session
session_start();
// loop through the session array with foreach
foreach($_SESSION['animals'] as $key=>$value)
{
// and print out the values
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
}
?>

The result of the above code will show you the session array, with the array keys.

Listing 13 Browser output from page2.php (listing-13.txt)
The value of $_SESSION['0'] is 'cat'
The value of $_SESSION['1'] is 'dog'
The value of $_SESSION['2'] is 'mouse'
The value of $_SESSION['3'] is 'bird'
The value of $_SESSION['4'] is 'crocodile'
The value of $_SESSION['5'] is 'wombat'
The value of $_SESSION['6'] is 'koala'
The value of $_SESSION['7'] is 'kangaroo'

You could of course, simply choose individual array members if your page2.php file looked like this..

Listing 14 page2.php
<?php
// begin the session
session_start();

Can I Store An Object In A Session?

Yes, using the following code we can include our class file as we would for any class. In page1.php we will instantiate a new object and put it in a session variable. Let’s us create a simple class file to include in our page1.php and page2.php scripts, we shall call it myclass.php.

Listing 15 myclass.php
<?php
// our class
class mySessionClass{
// The constructor, duh!
function __construct(){
}
// a function to set a property
function bar(){
return 'foo';
}
} // end of class
?>

In page1.php we include the class file and instantiate a new instance of the class directly into a session variable.

Listing 16 page1.php
<?php
// include the class file
include('myclass.php');
// begin the session
session_start();
// instantiate a new instance of the class mySessionClass
$_SESSION['foo']= new mySessionClass;
// echo a little message to say it is done
echo 'Setting value of foo to an object';
?>

Now we have the object in a session variable, we can go on to page2.php and use methods from mySessionClass.

Listing 17 page2.php
<?php
// include the class file
include('myclass.php');
// begin the session
session_start();

 

Can I Store A File Pointer In A Session?

The short answer is NO. Let’s create a page1.php and page2.php and see what happens. page1.php will look like this:

Listing 18 page1.php
<?php
// make it or break it
session_start();
// create a file pointer
$fp = fopen('my_file.txt', "r");
// set the file pointer to a session variable
$_SESSION['filePointer'] = $fp
?>
<a href="page2.php">link to page 2</a>

Everything here is fine. the variable is set and no error should be seen. page2.php should look like this:

Listing 19 page2.php
<?php
// make it or break it
error_reporting(E_ALL);
// begin our session
session_start();
// try to the read from the file pointer
$contents = fread ($_SESSION['filePointer'], filesize ($filename));
// close the file
fclose ($_SESSION['filePointer']);
// echo the files contents
echo "Contents: $contents"
?>

The above code will produce an error similar to this:

Listing 20 The warning caused by trying to store file pointers in sessions (listing-20.txt)
Notice: Undefined variable: filename in /html/page2.php on line 10
Warning: fread(): supplied argument is not a valid stream resource in /html/page2.php on line 10
Warning: fclose(): supplied argument is not a valid stream resource in /html/page2.php on line 13
Contents:

As you can see, no success on storing the file pointer.

echo $_SESSION['foo']->bar();
?>

Important Note: You MUST include the class definition on every page when you store an object

// echo a single member of the array
echo $_SESSION['animals'][3];
?>

This would simply retrieve the value for the 4th member of the array and print bird.

// Destroy the session.
session_destroy();
?>

How Are Sessions Stored?

The default behaviour for session storage is to save the session data in a file. This behaviour can be altered by changing the session.save_handler in your php.ini file. Options can be

  • files
  • mm
  • database
  • SQLite

As we saw earlier the format of saving session data in files looks like this:

Listing 21 Session data as stored on the filesystem (listing-21.txt)
|s:3:"bar";bar|s:3:"foo";foobar|s:5:"fubar";

If we choose we can have this stored in one of the options above. The mm option saves the session data into memory, this also gives significant speed increase and is often recommended by tutorials for fine tuning PHP and apache web server. Sessions may also be stored in a database. This option provides for greater manageability of sessions and allows the programmer to perform tasks such as counting of active sessions etc.

With the advent of PHP5, we now have SQLite bundled with PHP. If PHP is configured —with-sqlite, you will have access to saving sessions with a PHP native database, although SQLite is not truly a database, but a file abstraction layer with and SQL interface.

When Do Sessions Expire?

The default behaviour for sessions is to keep a session open indefinitely and only to expire a session when the browser is closed. This behaviour can be changed in the php.ini file by altering the line:

Listing 22 Keeping a session alive indefinitely (listing-22.txt)
session.cookie_lifetime = 0

If you wanted the session to finish in 5 minutes you would set this to:

Listing 23 Keeping a session alive for five minutes (listing-23.txt)
session.cookie_lifetime = 300

Remember to restart your web server after making this change.

 

How Can I Send Headers Then Start A Session?

Earlier we mentioned that you cannot send anything to the browser before session_start(). This is because when you set a header, you cannot do it twice. When you send text to the browser, headers are sent also.

However, PHP does provide a method to set headers, send text, and still be able to start your session. The ob_start() function allows you to buffer your output till you are ready to send content to the browser.

Listing 24 ob.php (listing-24.php)
<?php
// make it or break it
error_reporting(E_ALL);
// begin output buffering
ob_start();
// send a header
header ("Pragma: no-cache");
// send some text to the browser
echo 'This is a line of text';
// then we start our session
session_start();
// set the value of the session variable 'foo'
$_SESSION['foo']='bar';
// flush the buffer
ob_end_flush();
?>

Run this snippet of code and it will output the text

Listing 25 Browse output from using output buffering (listing-25.txt)
This is a line of text

First we sent a header with the no-cache, then echoed some text and finally started a session and set a session variable.

Session Security

This has a been an often debated point against the use of sessions. The reality is that a session, like any other programming method, will be as secure as you make it. With the advent of session came new ways in which a malicious user could hijack your session and your identity.

It is beyond the scope of this introduction to go in-depth into session security and is left as an exercise to the reader to hunt out resources for session security. An excellent place to begin is this fine article on PHP session security, and of course there is always, the PHP manual.

 

 

 

 

 

 

 

 

 

 
 
Add a Comment:
 
(You must be signed in to comment on an article. Not a member? Click here to register)
   
Title:

Comments: