Home
Web design
Software
Articles
Site Map

> Articles > PHP articles > Using sessions for user authorization

Using sessions for user authorization

  • 1. What are sections

Sections are used for sharing variables between different web pages accessed by the same user. Of course, somehow server has to know that it's the same user accessing different pages. Thus some way is required to identify the user.

There's a number of ways to identify the user, two most commonly used are:

  • Cookies. A technology used to save some data on user's hard disk. This way we can save a cookie with unique user identification number on user's hard disk, checking it every time user accesses the web page.
    • Positive side:
        The most easy way to identify the user, user may even restart his web browser and his id will still be the same.
    • Negative side:
        User may disable cookies in his web browser.
        Several people may use the same computer.

  • Transmitting user identification number in the URL, like
    http://www.digiways.com/something/?PHPSESID=12544631453132451251251235 and than adding
    "?PHPSESID=12544631453132451251251235" to each link on the page
    (where 12544631453132451251251235 is the user id).
    • Positive side:
        Doesn't depend on any browser settings
    • Negative side:
        Changes URL's making them hard to read.

By default PHP uses these two methods for transmitting user id. In the second case, if PHP was compiled with --enable-trans-sid and session.use_trans_sid option is enabled in php.ini, PHP adds user id to each link on the page automatically.

When PHP is configured properly, PHP sessions automatically choose the way to transmit user id (cookies if they are enabled in the user's browser and URL otherwise) and do all the work transparent to the programmer.

  • 2. Basical PHP sessions syntax

    start_session();
    
/* start_session() - starting the session, we have to put this line of code
in the very beginning of the web page, otherwise PHP won't be able to set HTTP header. */

    
session_register("variable_name");
    
/* Telling PHP to share the variable with the name "variable_name" between
sessions. */

Also, only global variables are shared between PHP scripts, so, the code to start the session and to share a variable would be:

    start_session();
    global 
$sharedVariable;
    
session_register("sharedVariable");

  • 3. Authorization.

First user has to enter his name and password to authenticate. It can be done in two ways.
  1. Using HTTP Authentication. Only possible if PHP is running as an Apache module.
    Sample code:

    header('WWW-Authenticate: Basic realm="DigiWays"');
    header("HTTP/1.0 401 Unauthorized");
    echo 
    "Please enter your username and password to access this page";
    /* Now we have username and password in $PHP_AUTH_USER and $PHP_AUTH_PW
    correspondingly. */

  2. Asking user to enter his name and password in the HTML form.
    Sample code:

    <form method="post">
    Username: <input type="text" name="username"><br>
    Password: <input type="password" name="password"><br>
    <input type="submit" value="Submit">
    </form>

  • 4. Validating user.

At some point we have to check if username/login is valid or not. This is usually done by keeping all usernames and md5 hash of their passwords in the database. For the simplicity let's assume that we have an associative array

aUserDatabase = array("username" => md5("password"), ...);

In real script we will have to access database to get this information.

Now, let us compose a web page where user will login and where the session will start.

login.php
<?
    session_start
(); // starting session
    // session variables must be global
    
global $strName$hashPassword$sessData;
    
// registering session variables
    
session_register("strName");
    
session_register("hashPassword");
    
session_register("sessData");
    
    
// checking if user is not authenticated
    
if (!isset($strName) || $aUserDatabase[$strName] != $hashPassword)
    {
        
// if not, checking if he just authenticated
        // but we haven't processed that information yet
        
global $HTTP_POST_VARS;
        if (isset(
$HTTP_POST_VARS["form_username"]))
        {
            
$strName $HTTP_POST_VARS["form_username"];
            
$hashPassword md5($HTTP_POST_VARS["form_password"]);
            
/* Using HTTP redirect to make user's web browser refresh this page.
            Otherwise, if user refreshes this page later, browser will ask him
            if he want's to resubmit form data, etc.
            Also PHP variable SID contains session id if cookie is not set.
            */
            
header("Location: http://www.mydomain.com/login.php?".SID);
            exit;
        }
?>
<form method="post">
Username: <input type="text" name="form_username"><br>
Password: <input type="password" name="form_password"><br>
<input type="submit" value="Submit">
</form>
<?    exit;
    }
?>
    Here's the part where user can get only after authorization.<br>
    Let's set some session variables to share. For instance,
<?
    
// this way we store the time when user authorized in $sessData["time"]
    
if (!isset($sessData["time"]))
        
$sessData["time"] = time();
        
    echo 
"You authorized at ".date("D M j G:i:s T Y"$sessData["time"])."<br>";
?>
    Links to other pages which will share this session.<br>
    <a href="anotherpage.php">anotherpage.php</a><br>
    <a href="logout.php">logout.php</a>

Note: If you want user to authorize using HTTP authorization, replace

    <form>
    ...
    </form>
with:
    <?
        header
    ('WWW-Authenticate: Basic realm="DigiWays"');
        
    header("HTTP/1.0 401 Unauthorized");
    ?>

and also replace $HTTP_POST_VARS["form_username"] and $HTTP_POST_VARS["form_password"]with $GLOBALS["PHP_AUTH_USER"] and $GLOBALS["PHP_AUTH_PW"] respectively.

  • 5. Accessing session from another page.

anotherpage.php
<?
    
// Same header to start the session and use it's variables
    
session_start(); // starting session
    // session variables must be global
    
global $strName$hashPassword$sessData;
    
// registering session variables
    
session_register("strName");
    
session_register("hashPassword");
    
session_register("sessData");

    
// checking if user is not authenticated
    
if (!isset($strName) || $aUserDatabase[$strName] != $hashPassword)
    {
        
// redirecting user to the login page
        
header("Location: http://www.mydomain.com/login.php");
        exit;
    }
?>
    Checking session variable:<br>
<?
    
echo "You authorized at ".date("D M j G:i:s T Y"$sessData["time"])."<br>";
?>    
    Links to other pages which will share this session.<br>
    <a href="login.php">login.php</a><br>
    <a href="logout.php">logout.php</a>

  • 6. Logout page.

logout.php
<?
    
// Same header to start the session and use it's variables
    
session_start(); // starting session
    // unregistering session variables
    
session_unregister("strName");
    
session_unregister("hashPassword");
    
session_unregister("sessData");
?>
    You have successfully loged out.<br>
    <a href="login.php">login.php</a>
  • 7. Notes.

    • It's a good idea to store the time when session was accessed last time, so, if used doesn't access any page in the session for some time, he logs out automatically.

    • It also can be usefull to check user IP and to logout user if it has changed, but only check first 3 numbers in the user IP. Don't check the 4th one. There're some http proxies that access web page each time from the different IP, but of course they are in the same subnet.

    • If you don't have session.use_trans_sid enabled in php.ini, the above example won't work. In that case we have to add PHP constant SID to each link (for example: <a href="anotherpage.php?<?=SID;?>">anotherpage.php</a>).

  • 8. Working sample.

When implementing this code, don't forget that we have to initialize the array $aUserDatabase.

Here is the working sample:

login.phplogin.phps ]
anotherpage.phpanotherpage.phps ]
logout.phplogout.phps ]



Copyright © Val Samko, DigiWays. Written by Valentin Samko mailto:val@digiways.com