PHP Sessions

Let's consider parameter use on the example of a site employing authorization procedure. When a user enters his or her name, a session must be initiated. This allows us to use session variables. A session is initiated by the session_start() function. If the function executes successfully, it returns true; otherwise, false is returned.

Now the PHP interpreter has to be informed which variables are to be saved in the session. This is done using the session_register() function, to which the variable name to be saved is passed as the parameter. Afterward, all the variables that have been placed into the session will be available from all pages of your site for the duration of the session.

Let's consider an example of a session. We'll create a file named session.php for this. The file contains a form to enter the user name, which will be saved in a session variabl:

<?php
  if (session_start())
   {
    print("OK");
   }
  $user=$UserName;
  session_register("user");
?>

<form action="session.php" method="get">
 User name: <input name="UserName">
 <input type="submit" name="sub" value="Go">
</form>

<a href="session1.php">This is a link</a>

Note that the PHP code is located at the very beginning of the file. This fact is important. To avoid any problems, the code for registering variables must be placed in the very beginning of the file, before any HTML tags. What problems are possible? Placing HTML code before the session start will generate an error and the variable will not be created.

The form for entering the user name passes the data entered to itself. I simply decided to save me some time and work and not create extra files.

The PHP code creates a session, and if it is successful, displays the OK message. Then a $user variable is created, into which the name entered by the user and stored in the global variable $UserName is copied.

The form also contains a reference to a script file named session1.php. When this reference is followed, a script will be executed that references the session variable. The script contains the following code:

<?php
  session_start();
  print("<P>Hello: $user");
?>

The first line of this code launches a session, and at this moment, the PHP interpreter determines the session identifier. In the second line the contents of the $user variable are displayed.

Run the session.php script in the browser. Enter a user name and click the OK button. At this moment, the session variable is assigned a value. You can now follow the reference and see that the session1.php displays the name entered. Although the variable value was not passed along with the reference, the session1.php script can see this name and displays it on the screen.

Session variables are automatically saved by the PHP interpreter and the programmer does not have to worry about this task. The question is for how long these variables are kept. This can be checked quite easily: close the browser and load the session1.php file again. This time the user name is not displayed. Even though very short time has passed, the session has changed, and now the variable is empty. This means a new session is created every time the script is run.

The shortcoming in the session1.php file is the no check is performed on whether the variable is set. Let's modify the code as shown in the next code:

<?php
  session_start();
?>

<HTML>
<HEAD>
<TITLE> Test page </TITLE>
</HEAD>

<BODY>

<?php
  if (!isset($user))
   {
    die("Authorization required");    
   }
  print("<P>Hello: $user");
?>

<hr>
<center>
<p>Hackish PHP
<br>© Michael Flenov 2005
</center><P>
</BODY>
<HTML> 

This example shows that a session is created at the very beginning of the file. The code to check the variable and use the session variable is located in the middle of the script file. The check for the variable being set is performed by the isset() function. If the $user variable does not exist for the script file, the function will return false. Actually, the check was done for the variable not existing, in which case the die() function is called, which displays a message about having to go through the authorization process on the site.

It is very important to understand that variables are created only in the register_globals directive in the php.ini file is set to on. Otherwise, the $_SESSION array has to be used. In this case, the code for creating a session variable will look like the following:

<?php
  if (session_start())
   {
    print("OK");
   }
  $_SESSION["user"] = $UserName;
?>
<form action="session2.php" method="get">
 User Name: <input name="UserName">
 <input type="submit" name="sub" value="Go">
</form>

<a href="session3.php">This is a link</a>

To test the example, save this code in a file named session2.php.

To use the variable, create a file named session3.php with the following code:

<?php
  if (!isset($_SESSION["user"]))
   {
    die("Authorization required");    
   }
  $t = $_SESSION["user"];
  print("<P>Hello: $t");
?>

How does the PHP interpreter know that a certain session is in progress now and that it will terminate when the browser is closed? Each session is assigned its own Session ID (SID). When a session is launched, this identified is stored in a cookie file, and following the execution of the session_start() function, each next page finds the SID and uses it to obtain access to the session parameters.

So far so good. Unfortunately, some users disable cookies fearing that sites collect their personal information. I personally consider this thinking paranoid. So what if a site owner finds out what pages I have visited? Moreover, this information can easily be obtained without resorting to cookies. A SID is created in any case and can be passed to any page using the POST or GET parameters with all variables stored on the server in a database, in which a user is identified by the SID. The Internet has been built on open standards, and this is the main problem security wise. It is impossible to make secret something that was not meant to be.

Run the session.php file and enter a user name. You will see that the URL string changes to the following: http://192.168.77.1/1/session2.php?PHPSESSID=8a22009f72339e71525288b33188703d&UserName=Tet The URL contains the PHPSESSID, which is the Session ID.

The identifier can be added to the URL explicitly. In the following example, the address to which the data from the form are sent is specified as session2.php?<?=SID?>.

<form action="session2.php?<?=SID?>" method="get">
 User Name: <input name="UserName">
 <input type="submit" name="sub" value="Go">
</form>

The <?=SID?> construction specifies that SID has to be added to the URL.

If you decide to use session variables without resorting to cookies, you must keep it in mind that displaying the identifier in the URL is far from being safe. If hackers overlook a user SID, they will be able to intercept the session. True, the format SID is in, it is only theoretically that a human can remember it. Someone with a photographic memory may, but not an average human. But the identifier can be intercepted programmatically. A Trojan program can choose the necessary part of or even the whole URL and send it to the perpetrator over the Internet.

Suppose that your site contains a forum in which certain users are allowed to work with the forum management scripts. Thus, when the administrator enters the forum he or she is given a SID, by which the system distinguishes the administrator from among other users. If hackers intercept the identifier, they will also obtain the administrator privileges, which is fraught with danger of loosing control over the forum and perhaps the whole site. An even worse development would be if hackers intercepted a session in which user credit card information is processed (e.g., an internet store session) over an open connection.

Consequently, using cookies is much safer for servers and, thus, for users. Let site owners know where on the Internet you had traveled, but hackers will have harder time intercepting your closed sessions.

To make users not fear cookies on your site, explain to them that cookies are necessary for their own security and are not used for any personal gain by the site owner.

Tag: PHP Development | Date:5/3/2010 10:17:54 PM