PHP Classes: Login

The following is a very basic encapsulation class for logging in users, logging out and checking if users are logged in or not.

It requires sessions and PHP 5 to work. The class assumes that passwords have been encrypted with the sha1 hash, so it hashes submitted passwords before comparing them to stored passwords in the database table.

If you are using sessions elsewhere in your site and you choose to make use of this class, make sure you don’t use $_SESSION['LOGIN'] for anything as this is the session variable used in the login class and reusing it elsewhere will interfere with it and compromise your security.

The schema for a basic “users” database table which this class will reference can be defined as follows:

CREATE TABLE users (
UserName VARCHAR(50),
Password VARCHAR(50),
PRIMARY KEY(UserName)
);

Now the code for the class itself:

Handle Login Class:

<?php
/*requires sessions*/
if(!isset($_SESSION))
session_start();
require_once 'cl_dbconnect.php';
class Login
{
private $UsersTable = 'users';
private $IdentityField = 'UserName';
private $PasswordField = 'Password';

private $DB; //DB connection var

public function __construct($current_id)
{
$this->DB = new DatabaseConnection();
}

public function login($username, $password)
{
$password = sha1($password);
$check = $this->DB->ExecuteSelectQueryRow("SELECT count(*) as user FROM $this->UsersTable WHERE $this->IdentityField = '$username' AND $this->PasswordField = '$password'");
if($check['user'] > 0)
{
$_SESSION['LOGIN'] = $username;
return true;
}
else
return false;
}

public function is_logged_in()
{
if(isset($_SESSION['LOGIN']))
return true;
else
return false;
}

public function logout()
{
unset($_SESSION['LOGIN']);
}
}
?>
Comments (0)
+ –