by Dinesh Thakur

Since PHP4, we hear a lot about sessions. Many people using PHP still unaware what they are and what they are for. Others, however, do not know how to use it wisely. This tutorial is an approach to theoretical and practical sessions. They will be presented by means of a simple example throughout this course. This is a space site secured by authentication.

What is a session?

A session is a technical mechanism to temporarily save the server information related to a user. This system has been especially invented to overcome the fact that the HTTP protocol is connectionless. Each time you open a new session, the user is given a session identifier. This identifier can be transmitted either GET (PHPSESSID added to the end of the URL) or POST Cookie (cookie on client) as the server configuration. The information will be transferred for their page by page by the server and not by the client. Thus, the security and integrity of the data is improved thereby see their availability throughout the session. A session can contain any type of data: number, string and even a table.

Unlike a database or a file system, the session stores information for a few minutes. This duration depends on the server configuration but is generally set at 24 minutes by default. The server creates files in a particular directory.

The sessions are particularly used for such applications:

• Members spaces and access with secure authentication.
• Managing a basket on an online sales site.
• Forms split on several pages.
• Storing information relating to user navigation (Preferred theme, languages ​​...).

The theory is fine but in practice how it goes? The next section explains the initialization and restoration of an open session.

Initialization (and restoration) of a session

PHP natively introduced a unique feature to start or continue a session. This is session_start (). This function takes no parameters and always returns true. It checks the status of the current session. If it does not exist, then the server creates it if he continues.

Initialization and restoration of session
<?php
    session_start();
?>

In the case of use of sessions with cookies, session_start () must be called before sending to the browser or risk seeing the famous display errors:

"Can not modify header information - headers already sent by ..." or "Can not send session cookie - headers already sent by ...". This is due to the fact that PHP can not send any cookie to the user because there's already had an output to the browser (echo (), print (), white space, html tag ...).

Note: you must call session_start () on each page using the login system.

Reading and writing a session

$_SESSION Array

When a session is created, it is empty by default. It therefore has no interest. We must therefore assign values ​​to save temporarily. For this, the PHP language sets up the $_SESSION superglobal. The term means that the superglobal Tabeau maximum visibility in scripts. This means that we can do globally as a local reference to a user function without having to pass a parameter. Table $ _SESSION can be indexed numerically but also associatively. Generally, it is preferred the second in order to give names clear session variables and meaningful.

The session writing

To register a new session variable, it's simple. You just need to add a key / value pair to the $_SESSION array as illustrated by the following example.

Declare and initialize a variable session
<?php
    // Start or restoration of the session
         session_start ();
   // Writing a new value in the table session
         $_SESSION ['login'] = 'Karan';
?>

$_SESSION Array, which was empty so far, has expanded dynamically and now contains a value (Karan) to the login associative key. A session variable is created.

Note Recall: in place of the string "Karan", we could have put a number, a boolean or a table for example.

Playing a session variable

After writing, it is the turn of reading. There is nothing simpler. To read the value of a session variable, you must simply call the session table with the appropriate key. The example below illustrates all that.

Playing a session variable
<?php
      // Start or restoration of the session
           session_start ();
      // Read a value of session table
           echo $_SESSION ['login'];
?>

This instruction will cause the screen to display the character string Karan.

Destroying a session

As mentioned above, the server destroys the session itself after a certain time if the session has not been renewed. However, it is possible to force its destruction by the session_destroy () function. This allows eg webmasters to provide a logout page logged members in their personal space. However, the use of session_destroy () alone is not very "clean". The following code shows a more correct way to end a session.

Clean and complete destruction of a session
<?php
      // Start or restoration of the session
           session_start ();
      // Reset the session table
     // We fully empty
           $_SESSION = Array ();
    // Destruction of the session
           session_destroy ();
    // Destruction of the session table
           unset ($_SESSION);
?>

To be convinced of the destruction of the session, you just have to try to view the contents of the session table using the print_r () function.

Configuring sessions on the server

A session remains open during a certain time. At most it will be that indicated by the php.ini directive session.gc_maxlifetime between two consecutive client clicks. It is recommended not to increase the value entered by default. But why? Simply becaufe if the session to a larger lifespan, it is exposed to piracy risks including session hijacking.

For the same security reasons, it is advisable to configure the server as follows:

PHP configuration recommended for sessions
session.use_cookies 1
session.use_only_cookies 1
session.use_trans_sid 0

This configuration however implies a total restriction for people not accepting cookies. Below, the meaning in the order of 3 previous configuration lines.

• The session ID is transmitted by a cookie.
• Only the cookie can transmit the session identifier.
• The transmitted PHPSESSID in the url is strictly refused.

Practical approach: develop a restricted access

Presentation of the practical case

This introduces a concrete case of use of sessions. This is a basic restricted access. Only a user is allowed to be logged but this example is the basis of creating a member zone. This is exactly the same. To achieve all this, we need two files: the form with the login script and the protected page. Start with the login form. The code is commented, there will be no more explanation.

Form authentication: authentification.php

Case study: identification form to a member's area
<?php
      // Definition of constants and variables
           define ('LOGIN', 'foo');
           define ('PASSWORD', 'tata');
           $errorMessage = '';

      // Test sending the form
           if (!empty ($_POST))
              {
                 // The IDs are transmitted?
                 if (!empty ( $_POST ['login']) && !empty ($_POST ['password']))
                    {
                       // Are they the same as the constants?
                       if ($_POST ['login'] !== LOGIN)
                           {
                               $errorMessage = 'Wrong login!';
                           }
                       elseif ($_POST ['password'] !== PASSWORD)
                          {
                              $errorMessage = 'Wrong password';
                          }
                       else
                         {
                              // Open the session
                              session_start ();
                             // It stores the login session
                             $_SESSION ['login'] = LOGIN;
                            // We redirected to the admin.php file
                            header ('Location: http://ecomputernotes.com');
                            exit ();
                          }
                  }
                      else
                       {
                           $errorMessage = 'Please enter your login please!';
                        }
            }
?>
<! DOCTYPE html PUBLIC "- // W3C // DTD XHTML 1.1 // EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml" xml: lang = "en">
       <Head>
           <title> Authentication Form </title>
       </Head>
             <body>
                <form action = "<?php echo htmlspecialchars ($_SERVER ['PHP_SELF']);?>" method = "post">
                     <fieldset>
                             <legend> sign in </legend>
                             <?php
                                   // Meeting are we a mistake?
                                   if (!empty ($errorMessage))
                                       {
                                            echo '<p>', htmlspecialchars ($errorMessage), '</ p> ';
                                       }
                             ?>
                            <p>
                                       <label for = "login"> login : </label>
                                       <input type = "text" name = "login" id = "login" value = "" />
                            </p>
                            <p>
                                 <label for = "password"> Password : </ label>
                               <input type = "password" name = "password" id = "password" value = "" />
                                 <input type = "submit" name = "submit" value = "Login" />
                          </p>
                     </fieldset>
                </form>
        </body>
</html>

Example protected page: admin.php

Example of a secure page with sessions
<?php
       // We extend the session
       session_start ();
      // It checks if the session variable exists and contains a value
      if (empty ($_SESSION ['login']))
         {
             // If no or zero, it redirects to the login form
             header ('Location: http://ecomputernotes.com');
             exit ();
         }
?>
<! DOCTYPE html PUBLIC "- // W3C // DTD XHTML 1.1 // EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml" xml: lang = "en">
     <Head>
           <title> Administration </title>
     </Head>
     <body>
     <?php
             // Here it is logged, it displays a message
            echo 'Welcome ', $_SESSION ['login'];
       ?>
    </body>
</html>

Little explanation: to protect each page of the administration, it is essential to add the first file header script entirely. It instantly redirects the user if he is not properly logged. Otherwise it displays the web page.