Building a Logout Class

The main function of the logout class is to log out a user and then redirect the user to the login page. On a programmatic level, the logout class terminates and destroys the session variables that the login class created for the user and also logs the exit time to the database. This article will show you how to create a logout class. It is part of a series on application framework components.

The class starts off with a constructor function that initializes some of the variables that will be used throughout the class. All of the classes that we will create throughout the next couple of articles will have a constructor function such as the ones we’ve seen so far. This is because this function basically sets up the database connection for the classes involved. The logout class has two functions, one of which is the constructor function and the other is the log_exit() function, that logs user exit time and date to the database:

<?php

class logout{

The constructor function has two sections. One deals with the database setup and the other simply sets up some variables for use in the class. All the global variables declared here are stored in the configuration file of the login class.  This excludes the $newid and $date_time values that are also shown. The class takes three parameters: the current date and time, the userid and the newid. Both the userid and newid will be stored during user login. Because the logout class simply updates an existing record, it requires these three parameters to accurately set the new values for the right user:

function logout($cdate,$uid,$nwid){
 
global $dbtype, $dbusername;
  global $dbpass, $dbhost,$newid;
  global $dbname, $dbtbl,$date_time;

We then link the database connection credentials and set up a database path or URL. This URL will then be used in subsequent connections to the database:

//set database connection details:
$this->dbtbl=$dbtbl;
$this ->dbp=$dbpath;
if($dbpath == null){
 
$this ->dbp=sprintf("%s://%s:%s@%s/%s", $dbtype, $dbusername, $dbpass, $dbhost,$dbname);
}

We then initialize some of the internal variables with the globally declared ones.  The newid variable, if you recall, was generated during login and is retrieved by the getnewid() function declared in the authorization class:

  //set logout status
  $this ->logoutstatus=FALSE;
  //set variables received from user
  $this->cdate=$date_time;
  $this->userid=$uid;
  $this->errmsg="";
  $this->newid=$nwid;
}

That’s it for the login class. The next function will do the actual recording of the users’ logout session.

{mospagebreak title=Recording the Logout Session}

The function does not take any parameters, but uses those declared and initialized in the constructor function:

  function log_exit(){
   
//connect to the db server with the user provided dbpath
   
$dbcon = new DBAL($this->dbp);
   
//update table with logout date
   
$query_updt = "UPDATE logtbl SET end_sess=’".$this->cdate."’
WHERE u_id=’".$this->userid."’ AND logid=’".$this->newid."’";
   
$result_updt =$dbcon->a_query($query_updt);
   
if(!$result_updt){
     
$this->errmsg="UPDATE query for the end_sess column
returned the following error: ".$dbcon->showError() . "n";
   
}else{
     
//subtract the dates and update the duration column
     
$sub = "SELECT date_sub(start_sess, INTERVAL end_sess  HOURS.MICROSECONDS ) as dur from logtbl WHERE u_id=’".$this-
>userid."’ AND logid=’".$this->newid."’";
     
$result=$dbcon->a_query($sub);
     
if($result){
       
//fetch the dur row that has been returned
       
$row=$result->fetchrow();
       
//update the duration column…
       
$q_update = "UPDATE logtbl SET duration = ‘".$row->dur."’
WHERE u_id=’".$this->userid."’ AND logid=’".$this->newid."’";
       
$result_q=$dbcon->a_query($q_update);
       
if(!$result_q){
         
$this->errmsg="UPDATE query for the duration column
returned the following error: ".$dbcon->showError() . "n";
       
}
     
}
   
}//first else
  }//endfunction
}//end class
?>

The fist couple of lines in the function connect to the database.

//connect to the db server with the user provided dbpath
$dbcon = new DBAL($this->dbp);

Then it sets up the first of three SQL queries. The query is basically an update query that adds today’s date and time to the user with the given userid:

//update table with logout date
$query_updt = "UPDATE logtbl SET end_sess=’".$this->cdate."’ WHERE u_id=’".$this->userid."’ AND logid=’".$this->newid."’";
$result_updt =$dbcon->a_query($query_updt);

After executing the query, the code checks to see if the result that is returned is false. If so, a very elaborate error message is generated, stating which query caused the error since there are three of them in this function:

if(!$result_updt){
 
$this->errmsg="UPDATE query for the end_sess column returned the following error: ".$dbcon->showError() . "n";

If the update query result is true, then the next query is executed. This query’s aim is to calculate the time difference between the two datetime columns and store the result in a row called dur. To make sure that the right date time column values are retrieved, the query uses the WHERE clause in which it specifies which user and logid should be checked. The user is identified by the userid variable and the logid identifies the precise record in the log table that should be checked:

}else{
 
//subtract the dates and update the duration column
 
$sub = "SELECT date_sub(start_sess, INTERVAL end_sess  HOURS.MICROSECONDS ) as dur from logtbl WHERE u_id=’".$this-
>userid."’ AND logid=’".$this->newid."’";
 
$result=$dbcon->a_query($sub);

If the result of the query is true, then the duration column of the log table is updated. Again the userid and log table id are used to make sure that the correct row is updated:

if($result){
 
//fetch the dur row that has been returned
 
$row=$result->fetchrow();
 
//update the duration column…
 
$q_update = "UPDATE logtbl SET duration = ‘".$row->dur."’ WHERE
u_id=’".$this->userid."’ AND logid=’".$this->newid."’";
 
$result_q=$dbcon->a_query($q_update);

If the user or log id was not found, the following error message is stored in the errmsg variable:

    if(!$result_q){
 
$this->errmsg="UPDATE query for the duration column returned
the following error: ".$dbcon->showError() . "n";
      }
    }
  }//first else
}//endfunction

Just a quick word of caution: I’ve used a function called DATE_SUB() that might not be available in your version of MYSQL, so check to make sure that it is available before running this code. I believe DATE_SUB() is also vendor specific, so it might not work in other database environments.

That’s all there is to the logout class.  Next we will look at the database tables behind the two classes.

{mospagebreak title=The Database Tables}

The database table that is used to track user log in and log out is very simple. Below is the SQL to create a table for it:

# Host: localhost
# Database: intranet
# Table: ‘logtbl’
#

CREATE TABLE `logtbl` (
  `logid` int(4) NOT NULL auto_increment,
  `u_id` int(4) NOT NULL default ‘0’,
  `start_sess` datetime NOT NULL default ‘0000-00-00 00:00:00′,
  `end_sess` datetime NOT NULL default ‘0000-00-00 00:00:00′,
  `duration` varchar(20) NOT NULL default ”,
  PRIMARY KEY  (`logid`)
) TYPE=MyISAM;

It has the following fields:

logid          – Stores a unique number for each new record
u_id           – Stores the user id of the currently logged in user
start_sess – time and date of the user log in
end_sess   – time and date of user log out
duration     – duration in hours, minutes and seconds between start_sess and end_sess date time values

The all important users table contains the usernames and passwords of all the intranet users.  Below is the SQL that will create this table. I’ve also included sample data for the table. Notice the format in which the email addresses are written. The checkemail() function in the validate class that we discussed in earlier articles checks for this format to verify the validity of a email address:

# Host: localhost
# Database: intranet
# Table: ‘users’
#

CREATE TABLE `users` (
  `uid` int(11) NOT NULL auto_increment,
  `name` varchar(20) NOT NULL default ”,
  `sname` varchar(20) NOT NULL default ”,
  `upass` varchar(8) NOT NULL default ”,
  `access_level` enum(‘admin’,’regular’) NOT NULL default
‘regular’,
  `email` varchar(100) NOT NULL default ”,
  `depid` int(2) NOT NULL default ‘0’,
  `isActive` int(2) NOT NULL default ‘0’,
  PRIMARY KEY  (`uid`)
) TYPE=MyISAM

The table has the following fields:

uid          – creates a unique id for every user
name      – stores the name of the user
sname    – stores the surname of the user
upass     – stores the user password
access   – stores the access level either admin or normal
email     – stores the email address of the user
depid     – stores the department id of the user
isactive – sets the user account to either  1 for active or 0 for  inactive

And here’s the sample data for the table:

INSERT INTO `users` VALUES (1, ‘mubasen’, ‘gaseb’, ‘pass’,
‘admin’, ‘mubasen.gaseb@damaranet.com’, 3, 1);
INSERT INTO `users` VALUES (2, ‘dantago’, ‘nanub’, ‘sunday’,
‘regular’, ‘dantago.nanub@damaranet.com’, 1, 1);
INSERT INTO `users` VALUES (3, ‘axaro’, ‘garoeb’, ‘monday’,
‘regular’, ‘axaro.garoeb@damaranet.com’, 2, 1);
INSERT INTO `users` VALUES (4, ‘koro’, ‘garises’, ‘teusday’,
‘admin’, ‘koro.garises@damaranet.com’, 1, 1);
INSERT INTO `users` VALUES (5, ‘saridao’, ‘taurob’, ‘thursday’,
‘admin’, ‘saridao.taurob@damaranet.com’, 2, 1);

{mospagebreak title=Testing the Classes}

Let’s test the login/logout classes and see if they work. Create a new PHP document and add the following code. I’ve commented on the code that I used here so it should be easy to understand:

<?php
error_reporting(E_ALL &~E_NOTICE);
// First load the DB.php class from PEAR
require_once ‘DB.php';
// Now load our DBAL class
require_once(‘../DB/db.class.php’);
//load the config file for the login class
require_once(‘config/login.conf.php’);
//finally load the login class itself.
require_once(‘login.class.php’); /*
$emails =mysql_escape_string($_POST['email']);
$pass=mysql_escape_string($_POST['pass']); */
if(isset($_POST['sub'])){
  $emails=$_POST['email'];
  $pass=$_POST['pw'];
  $dp=$dbpath;
  echo "<b>Contents of db connection variable:</b>";
  print_r($dp);
  echo ‘<br>';
  $a = new authorization($emails,$dp,$pass);
  $y = $a->check_user();
  if($y){
    $myid=$a->getid();
    $myname=$a->getname();
    echo "<b>Userid:</b> ".$myid." <b>Username: </b>".$myname;
    echo ‘<table>
    <tr>
      <td><a
href="../../app_fwork/authorize/logout.class.php">Logout</a></td>
    </tr>';
    echo ‘</table>';
  }else{
    $err=$a->showerror();
    echo $err."ERR";
  }
  exit;
}
?>
<html>
<head></head>
 <body>
  <form id="form1" name="form1" method="post" action="<? $_SERVER
['PHP_SELF']?>">
    <table width="100%" border="0">
      <tr>
        <td colspan="2"><center>Please login below:</center></td>
      </tr>
      <?php if(!empty($errmsg)){ ?>
      <tr>
        <td width="10%" bgcolor="#FF0000"><b>ERROR!</b></td>
        <td width="90%"><?php echo $errmsg;?></a></td>
      </tr>
<?php } ?>
<?php if(isset($lmsg)){ ?>
      <tr>
        <td width="10%" ><b>Logout message</b></td>
        <td width="90%"><?php echo "You’ve been logged out.’";?
></td>
      </tr>
<?php } ?>
      <tr>
        <td><b>Email:</b></td>
        <td><input name="email" type="text" class="input200"
id="email" value="mubasen.gaseb@damaranet.com" size="50"/></td>
      </tr>
      <tr>
        <td><b>Password:</b></td>
        <td><label>
          <input name="pw" type="password" class="input200"
id="pw" value="pass" />
          <input name="sub" type="hidden" value="sub" />
        </label></td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td><a
href="../../app_fwork/authorize/logout.class.php"></a></td>
      </tr>
      <tr>
        <td><a
href="../../app_fwork/DB/validate.class.php"></a></td>
        <td><label>
          <input type="submit" name="Submit" value="Login" />
        </label></td>
      </tr>
    </table>
   </form>
</body>
</html>

The HTML form collects the username and password and then compares it with the information in the database. This is done through the checkuser() function defined in the login class. Upon successful authentication the username and id are displayed together with the contents of the connection variable. The id of the user is received through the getid() function of the login class; similarly, the username is received through the getname() function. Below is a screenshot of the login test:

Conclusion

There’s a couple of things that I haven’t done here in terms of security. The first is that I did not hash the passwords that are stored in the database, so please make sure that you implement this safety measure. Use either MD5() or Crypt() to encrypt the passwords. If there are other things that I have not done correctly than please, by all means, correct them before using the code. It is also a good idea to keep both the login application and users table separate from the other applications and databases. The users table should be in a separate database from the rest of the tables.

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye