#native_company# #native_desc#
#native_cta#

Session Management

By Jeff
on September 23, 2001

Version: 1

Type: Function

Category: HTML

License: GNU General Public License

Description: Provides session management without the use of cookies. Logs people in and out. Prevents duplicate log-ins. Forces log-out of expired sessions. Changes session variable at every webpage viewed or refreshed. Very robust.

<?
/*---------------------------------------------------------------------------------

Written in 2001 by [email protected]

I wrote this because I needed a program that provided session protection on a set of
web pages but was specifically not allowed to set cookies. It is simple to use and as far as I have seen, very robust.  Feel free to use this or make adaptations to it as needed. Please email me with any updates you make, any questions you have, what you think of this program, or to tell me what you end up using this for.

PHP is Great!

------------------------------------------------------------------------------------

Important functions:

connect: Connects to the database.

login:   Deletes expired sessions. Checks Username and Password for validity. If valid,it checks to see if that user is already logged in. If the user is already logged in it assumes that a security breach has occured so it logs the user out
and freezes the user account. Otherwise, if the user is not logged in it logs them
in and passes back a session variable.

updateSession: Deletes expired sessions. Looks for session passed to it. If found, it
passes back a new one thus constantly changing the session variable. If session was not found it passes back false.

logout:  Logs the user out and deletes the session variable.

checkAccess: This is an optional function that passes back the access level a user might have.

-----------------------------------------------------------------------------------

Configuration:

function connect($database="internet"){ :  Find this line and set the default database name on this line

$expirationtime=time()-1200; : Find this line and set the length of time in seconds that a user can remain inactive but still be logged into the web page. Currently it is set for 20 mins.

$length=8; :  Find this line and set it to the desired length of the session variable. I believe that 8 characters is the bare minimum. The maximum would depend on how long you have set the session field in the database.  50 is a good  number.

------------------------------------------------------------------------------------

Usage:

Example log-in page:

<?

include ("sessions.php");

if ($mode=="login"){

$db=connect();
$session=login($db,$username,$password);
if ($session){
header ("Location:index.php?session=$session");
}
}
print <<<EOF
<form method="POST" action="login.php">
<p align="center"><b>Please Login</b></p>
<p align="center"><b>User Name </b><input type="text" name="username" size="20" tabindex="1"><br>
<b>Password&nbsp;&nbsp;&nbsp; </b><input type="password" name="password" size="20" tabindex="2"></p>
<p align="center"><input type="submit" value="Submit" name="submit" tabindex="3">&nbsp;
<input type="reset" value="Reset" name="reset" tabindex="4">
<input type="hidden" name="mode" value="login"></p>
</form>
EOF;

?>


At the top of every page you want secure place something like the following code.

include ("sessions.php");
$db=connect();
$session=updateSession($db,$session);
if (!$session){header ("Location:login.php");}

If you want to also access the security levels place something like this at the top instead

include ("sessions.php");
$db=connect();
$session=updateSession($db,$session);
if (!$session){header ("Location:login.php");}
$access=checkAccess($db,$session);
if ($access < 90){header("Location:forbidden.php?session=$session");}

Remember, that you must include something like the above code on every page you want secure AND you must pass the session variable along from  page to page.

--------------------------------------------------------------------------------------

Minimum Database Requirements:

Below is the table creation script for a MYSQL database.

# phpMyAdmin MySQL-Dump
# http://phpwizard.net/phpMyAdmin/
#
# Host: localhost Database : internet

# --------------------------------------------------------
#
# Table structure for table 'sessions'
#

DROP TABLE IF EXISTS sessions;
CREATE TABLE sessions (
   Session varchar(200) NOT NULL,
   UserID int(10) unsigned DEFAULT '0' NOT NULL,
   UserName varchar(50) NOT NULL,
   CorporateDivision varchar(50) NOT NULL,
   Time varchar(200) NOT NULL
);


# --------------------------------------------------------
#
# Table structure for table 'userlog'
#

DROP TABLE IF EXISTS userlog;
CREATE TABLE userlog (
   UserLogID int(10) unsigned NOT NULL auto_increment,
   UserID int(10) unsigned DEFAULT '0' NOT NULL,
   UserName varchar(50) NOT NULL,
   CorporateDivision varchar(50) NOT NULL,
   Time varchar(75) NOT NULL,
   Log varchar(50) NOT NULL,
   PRIMARY KEY (UserLogID)
);


# --------------------------------------------------------
#
# Table structure for table 'users'
#

DROP TABLE IF EXISTS users;
CREATE TABLE users (
   UserID int(10) unsigned NOT NULL auto_increment,
   UserName varchar(50) NOT NULL,
   Password varchar(50) NOT NULL,
   CorporateDivision varchar(50) NOT NULL,
   AccessPermitted int(10) unsigned DEFAULT '0' NOT NULL,
   PRIMARY KEY (UserID)
);


--------------------------------------------------------------------------------------

Follow ups:

Please note that by accessing the session table you can tell who is currently logged-in,
and from where. Useful for reports perhaps?

-----------------------------------------------------------------------------------*/


//Program starts here:


//----------------------------------------------------------------------------------// Connect to the database.
//----------------------------------------------------------------------------------

function connect($database="internet"){

     $db=mysql_connect("localhost","root","");

     if (! mysql_select_db("$database")){
           $db="";
           print ("<p><b><center>Unable to connect to database. Please contact the Administrator</b></center>");
           exit();
     }

return ($db);
}



//----------------------------------------------------------------------------------
// Look for, log out, and delete all old sessions
//----------------------------------------------------------------------------------

function checkSession($db){

    $expirationtime=time()-1200;// set this to seconds of inactivity before forced logout (20mins)
    $query = "SELECT * From sessions WHERE Time < '$expirationtime'";
    $result=mysql_query($query,$db);

    while($row=mysql_fetch_row($result)){
       $session=$row[0];
       $userid=$row[1];
       $username=$row[2];
       $corporatedivision=$row[3];
       deleteSession($db,$session);
       writeLog($db,$userid,$username,$corporatedivision,"2");
    }

return;
}



//----------------------------------------------------------------------------------
// Update session time if it exists.
//----------------------------------------------------------------------------------

function updateSession($db,$session){

     checkSession($db);

     $query="SELECT * FROM sessions WHERE Session='$session'";
     $result=mysql_query($query,$db);
     $row=mysql_fetch_row($result);

     if ($row[0]){
         $userid=$row[1];
         $username=$row[2];
         $corporatedivision=$row[3];
         $accesspermitted=$row[5];
         deleteSession($db,$session);
         $session=setSession($db,$username,$corporatedivision,$userid,$accesspermitted);
     }else{
         $session=false;
     }

return $session;
}



//----------------------------------------------------------------------------------
// Log user in. If user already has a session then security risk.  Throw them out.
//----------------------------------------------------------------------------------

function login($db,$passedusername,$passedpassword){

     checkSession($db);

     $query="SELECT * FROM users WHERE UserName = '$passedusername'";
     $result=mysql_query($query,$db);
     $row=mysql_fetch_row($result);

     if ($row[0]){
         $userid=$row[0];
         $username=$row[1];
         $password=$row[2];
         $corporatedivision=$row[3];
         $accesspermitted=$row[4];

         if($password==$passedpassword AND $accesspermitted>0){

              $session=checkUser($db,$userid); //check to see if user is already logged in

              if ($session){
                  deleteSession($db,$session);//Force the user out if already logged in
                  writeLog($db,$userid,$username,$corporatedivision,'4');
                  $query="UPDATE users SET AccessPermitted = 0 WHERE UserID = $userid";
                  mysql_query($query,$db);
                  print "<p><center><b>Emergency system notice: Your account is already in use on this system.";
                  print "<br>For security reasons your account is now frozen.";
                  print "<br>Consult your system administrator to re-activate your account.</b></center>";
                  exit();
              }else{
                  writeLog($db,$userid,$username,$corporatedivision,'1');
                  $session=setSession($db,$username,$corporatedivision,$userid,$accesspermitted);
              }

         }else{
              $session=false;
         }

     }else{
         $session=false;
     }
return $session;
}



//----------------------------------------------------------------------------------
// Set a session and insert session into session table.
//----------------------------------------------------------------------------------

function setSession($db,$username,$corporatedivision,$userid,$accesspermitted){

     $time=time();
     $length=8;// set this to the length of session variable desired
     $session="";
     mt_srand(time());

     $sessionstring="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

     $achar=strlen($sessionstring)-1;

     for ($i=0;$i<$length;$i++){
          $session.=$sessionstring[mt_rand(0,$achar)];
     }

     $query = "INSERT INTO sessions (Session,UserID,UserName,CorporateDivision,Time,AccessPermitted) VALUES ('$session',$userid,'$username','$corporatedivision','$time',$accesspermitted)";
     mysql_query($query,$db);

return $session;
}



//----------------------------------------------------------------------------------
// Delete a session and return.
//----------------------------------------------------------------------------------

function deleteSession($db,$session){

     $query="DELETE FROM sessions WHERE session = '$session'";
     mysql_query($query,$db);

return;
}


//----------------------------------------------------------------------------------
// Return the access level for a user . These functions only care about access = 0
//----------------------------------------------------------------------------------

function checkAccess($db,$session){

     $query="SELECT * FROM sessions WHERE Session = '$session'";
     $result=mysql_query($query,$db);
     $row=mysql_fetch_row($result);

     if ($row[5]){
         $access=$row[5];
     }else{
         $access = 0;
     }

return $access;
}

//-----------------------------------------------------------------------------------
// Check the user to see if they are already logged in.
//-----------------------------------------------------------------------------------

function checkUser($db,$userid){

     $query="SELECT * FROM sessions WHERE UserID = $userid";
     $result=mysql_query($query,$db);
     $row=mysql_fetch_row($result);

     if ($row[0]){
         $session=$row[0];
     }else{
         $session = false;
     }

return $session;
}



//----------------------------------------------------------------------------------
// Write to the user log depending on what the user is doing.
//----------------------------------------------------------------------------------

function writeLog($db,$userid,$username,$costcenter,$log){

     switch ($log){

          case 1:
               $log="Log-in";
               break;
          case 2:
               $log="Session time-out";
               break;
          case 3:
               $log="Log-out";
               break;
          case 4:
               $log="Dupe Force Out";
               break;
     }

     $time=time();
     $query="INSERT INTO userlog (UserID,UserName,CorporateDivision,Time,Log) VALUES ('$userid','$username','$corporatedivision',$time,'$log')";
     mysql_query($query,$db);

return;
}



//----------------------------------------------------------------------------------
// Log the user out when they click on the log-out button
//----------------------------------------------------------------------------------

function logout($db,$session){

     $query="SELECT * FROM sessions WHERE Session = '$session'";
     $result=mysql_query($query,$db);
     $row=mysql_fetch_row($result);

     if ($row[1]){
         $userid=$row[1];
         $username=$row[2];
         $corporatedivision=$row[3];
         writeLog($db,$userid,$username,$corporatedivision,"3");
         deleteSession($db,$session);
     }

return;
}
?>