Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

Setting a session after authentication

Sunday, November 9th, 2014 by Servage

2The following post is shedding a little light on some good session and authentication principles. Often, it’s normal procedure to create a session on every request where the requesting client does not have a session already. However, I  like to assign sessions only after login – or create a new session after login. This is because I will eventually be doing login over HTTPS and would like to prevent hackers from hijacking the sessions from users that have authenticated.

Consider the below code script for setting up a new session after successful authentication.

<?php //authenticate2.php
 require_once 'login.php';
 $db_server = mysql_connect($db_hostname, $db_username, $db_password);
  if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
  mysql_select_db($db_database)
  or die("Unable to select database: " . mysql_error());
  if (isset($_SERVER['PHP_AUTH_USER']) &&
  isset($_SERVER['PHP_AUTH_PW']))
   {
    $un_temp = mysql_entities_fix_string($_SERVER['PHP_AUTH_USER']);
    $pw_temp = mysql_entities_fix_string($_SERVER['PHP_AUTH_PW']);
    $query = "SELECT * FROM users WHERE username='$un_temp'";
    $result = mysql_query($query);
    if (!$result) die("Database access failed: " . mysql_error());
    elseif (mysql_num_rows($result))
     {
      $row = mysql_fetch_row($result);
      $salt1 = "qm&h*";
      $salt2 = "pg!@";
      $token = md5("$salt1$pw_temp$salt2");
      if ($token == $row[3])
       {
        session_start();
        $_SESSION['username'] = $un_temp;
        $_SESSION['password'] = $pw_temp;
        $_SESSION['forename'] = $row[0];
        $_SESSION['surname'] = $row[1];
        echo "$row[0] $row[1] : Hi $row[0],
        you are now logged in as '$row[2]'";
        die ("<p><a href=continue.php>Click here to continue</a></p>");
       }
      else die("Invalid username/password combination");
     }
    <
    else
     {
      header('WWW-Authenticate: Basic realm="Restricted Section"');
      header('HTTP/1.0 401 Unauthorized');
      die ("Please enter your username and password");
     }
    function mysql_entities_fix_string($string)
     {
      return htmlentities(mysql_fix_string($string));
     }
      function mysql_fix_string($string)
     {
      if (get_magic_quotes_gpc()) $string = stripslashes($string);
      return mysql_real_escape_string($string);
     }
?>

One other addition to the program is the “Click here to continue” link with a destination URL of continue.php. This will be used to illustrate how the session will transfer to another program or PHP web page.

Retrieving session variables

<?php // continue.php
 session_start();
 if (isset($_SESSION['username']))
  {
   $username = $_SESSION['username'];
   $password = $_SESSION['password'];
   $forename = $_SESSION['forename'];
   $surname = $_SESSION['surname'];
   echo "Welcome back $forename.<br />
   Your full name is $forename $surname.<br />
   Your username is '$username'
   and your password is '$password'.";
  }
 else echo "Please <a href=authenticate2.php>click here</a> to log in.";
?>

Now you are ready to call up authenticate2.php into your browser, enter a username of “bsmith” and password of “mysecret” (or “pjones” and “acrobat”) when prompted, and click on the link to load in continue.php.

Sessions neatly confine the extensive code required to authenticate and log in a user to a single program. Once a user has been authenticated and you have created a session, your program code becomes very simple indeed. You only need to call up session_start and look up any variables to which you need access from $_SESSION.

A quick test of whether $_SESSION['username'] has a value is enough to let you know that the current user is authenticated, because session variables are stored on the server (unlike cookies, which are stored on the web browser) and can therefore be trusted.

If $_SESSION['username'] has not been assigned a value, no session is active, so the last line of code directs users to the login page at authenticate2.php.

The continue.php program prints back the value of the user’s password to show you how session variables work. In practice, you already know that the user is logged in, so it should not be necessary to keep track of (or display) any passwords, and doing so would be a security risk – it is only included here as an example.

References & more reading

Setting a session after authentication, 3.6 out of 5 based on 5 ratings
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.