Showing posts with label authenticate. Show all posts
Showing posts with label authenticate. Show all posts

Tuesday, 7 August 2012

OOP PHP Authentication Class

This class relies upon the existence of a databases class, such as the one listed here, to go away and check of the username and password match. If they do, a session and cookie is created.


<?php
require_once 'database.class.php';

class authenticate
{
public $id;
private $username;
private $password;
private $db;

function __construct()
{
$this->db = new database;
}

function login($u, $p)
{
$this->username = mysql_real_escape_string($u);
$this->password = mysql_real_escape_string(md5($p));
$q = "SELECT * FROM users WHERE username='{$this->username}' AND password='{$this->password}'";
$result = $this->db->query($q);
if($result)
{

    $this->id = $result->id;
    $this->username = $result->username;

$this->createSessionAndCookies();
}
else
{
$this->destroySessionAndCookies();
}
}

function logout()
{
$this->destroySessionAndCookies();
}

private function createSessionAndCookies()
{
@session_start();
$_SESSION['AUTH_ID'] = $this->id;
$_SESSION['AUTH_USERNAME'] = $this->username;
$expire=time()+3600*24*30;
setcookie('AUTH_ID', $this->id, $expire);
setcookie('AUTH_USERNAME', $this->username, $expire);
echo 'session and cookie created';
}

private function destroySessionAndCookies()
{
unset($_SESSION['AUTH_ID']);
unset($_SESSION['AUTH_USERNAME']);
session_destroy();
setcookie('AUTH_ID', '', time()-3600);
setcookie('AUTH_USERNAME', '', time()-3600);
echo 'session and cookie destroyed';
}

function __destruct()
{

}
}
?>