Difference between revisions of "Understanding PHP Sessions"

From Techotopia
Jump to: navigation, search
(Writing PHP Session Data to a File)
(Reading a Saved PHP Session)
Line 105: Line 105:
  
 
== Reading a Saved PHP Session ==
 
== Reading a Saved PHP Session ==
 +
 +
Once session data has been written to a file it can be read back in, decode and applied to the current session. This is achived using the ''session_decode()'' function:
 +
 +
<pre>
 +
<?php

Revision as of 18:12, 6 June 2007

In the previous chapter (PHP and Cookies - Creating, Reading and Writing) we looked at the use of cookies to maintain state. In that chapter we also mentioned the use of PHP seesions as an alternative to the use of cookies. We also provided an overview of the difference between cookies and PHP sessions.

In this chapter we will explore the concept of PHP sessions in more detail and provide some examples of how to create and use session.


Contents


What is a PHP Session?

PHP Sessions allow web pages to be treated as a group, allowing variables to be shared betweem different pages. One of the weaknesses of cookies is that the cookie is stored on the user's computer (by user we mean the person with the browser visiting your web site). This provides the user the ability to access, view and modify that cookie for potentially nefarious purposes. PHP sessions, on the other hand, store only an ID cookie on the users system which is used to reference the session file on the server. As such, the user has no access to the content of the session file thereby providing a secure alternative to cookies. PHP sessions also work when the user has disabled the browser's cookie support. In this situation it includes the session ID information in the web page URLs.

Creating a PHP Session

PHP sessions are created using the session_start() function and should the first function call of the PHP script on your web page (i.e before any output is written to the output stream).

The following example demonstrates the creation of a PHP session:

<?php
       start_session();
?>
<html>
<head>
<title>A PHP Session Example</title>
</head>
<body>
</body>
</html>

Creating and Reading PHP Session Variables

Variables can be assigned to a session using the $_SESSION array. This is a global array that is accessible to all the pages on your web site. The is also an associative array (see PHP Arrays for details of using arrays in PHP) and as such it is possible to access array elements using the variable name as an index.

Session variables can be any type of data such as strings, numbers, arrays and objects.

Session variables can be defined using a number of mechanisms. Variables can be assigned directly to the $_SESSION array using the assignment operating and variable name:

<?php
     $_SESSION['userName'] = 'JohnW';
?>

Another option is to use the PHP session_register() function. session_register() takes two arguments, the string represnting the variable name, andthe value to be assigned to the variable:

<?php
session_register('username', 'JohnW');
?>

Session variables are accessed by using the variable name as an index key into the $_SESSION array. The session_is_registered() function can also be used to make sure the variable exists before attempting to read the value. For example:

<?php
session_start();
?>
<html>
<head>
<title>Simple HTML Form</title>
</head>
<body>
<?php
        if (session_is_registered('userName')
        {
                $_SESSION['userName'] = 'Neil';
                echo 'userName = ' . $_SESSION['userName'];
        }
?>

</body>
</html>

The resulting output from the above page will read:

userName = Neil

The same PHP code to read the value can be used on any page on your server to access the current value of the variable.

Writing PHP Session Data to a File

Session data only stays active on the web server until it expires or the session is deleted. Once deleted, all the data associated with the session is lost. A snapshot of the session data can, however, be taken at any time and written out to a file. Once saved it can be reloaded when required.

To save a session state the session_encode() function is used combined the PHP file I/O functions (see PHP, Filesystems and File I/O for details of reading and writing files). The session_encode() function returns an encoded string containing the session data. Once this string has been obtained it can be written to a file:

<?php

      $_SESSION['userName'] = 'JohnW';
      $_SESSION['emailAddress'] = '[email protected]';

      $session_data = session_encode(); // Get the session data

      $filehandle = fopen ('/tmp/php_session.txt', 'w+'); // open a file write session data 

      fwrite ($filehandle, $session_data); // write the session data to file

      fclose ($filehandle);

?>

If you are interested in seeing what the encoded session data looks like you can load it into a text editor. The above example creates the following data in the file:

userName|s:5:"JohnW";emailAddress|s:16:"[email protected]";

Reading a Saved PHP Session

Once session data has been written to a file it can be read back in, decode and applied to the current session. This is achived using the session_decode() function:

<?php