Simple PHP/MySQL authentication class
Here is a simple PHP/MySQL authentication script (class) that is secure and easy to use. The class features:
- Login form
- Password recovery with basic email injection protection
- Optional md5 password encryption
- MySQL logon table creation
- MySQL injection protection
- Page password protection
MySQL table
The only requirement for the table is that the username stores emails, because it is used for password recovery.
CREATE TABLE `logon` ( `userid` int(11) NOT NULL auto_increment, `useremail` varchar(50) NOT NULL default '', `password` varchar(50) NOT NULL default '', `userlevel` int(1) NOT NULL default '0', PRIMARY KEY (`userid`) ) TYPE=MyISAM
PHP Class (class.login.php)
IMPORTANT: Make sure to fill in the database info. See comments for the details.
//start session
session_start();
class logmein {
//database setup
//MAKE SURE TO FILL IN DATABASE INFO
var $hostname_logon = ' '; //Database server LOCATION
var $database_logon = ' '; //Database NAME
var $username_logon = ' '; //Database USERNAME
var $password_logon = ' '; //Database PASSWORD
//table fields
var $user_table = ''; //Users table name
var $user_column = ''; //USERNAME column (value MUST be valid email)
var $pass_column = ''; //PASSWORD column
var $user_level = ''; //(optional) userlevel column
//encryption
var $encrypt = false; //set to true to use md5 encryption for the password
//connect to database
function dbconnect(){
$connections = mysql_connect($this->hostname_logon, $this->username_logon, $this->password_logon) or die ('Unabale to connect to the database');
mysql_select_db($this->database_logon) or die ('Unable to select database!');
return;
}
//login function
function login($table, $username, $password){
//make sure table name is set
if($this->user_table == ""){
$this->user_table = $table;
}
//check if encryption is used
if($this->encrypt == true){
$password = md5($password);
}
//execute login via qry function that prevents MySQL injections
$result = $this->qry("SELECT * FROM ".$this->user_table." WHERE ".$this->user_column."='?' AND ".$this->pass_column." = '?';" , $username, $password);
$row=mysql_fetch_assoc($result);
if($row != "Error"){
if($row[$this->user_column] !="" && $row[$this->pass_column] !=""){
//register sessions
//you can add additional sessions here if needed
$_SESSION['loggedin'] = $row[$this->pass_column];
//userlevel session is optional. Use it if you have different user levels
$_SESSION['userlevel'] = $row[$this->user_level];
return true;
}else{
session_destroy();
return false;
}
}else{
return false;
}
}
//prevent injection
function qry($query) {
$this->dbconnect();
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("?", "%s", $query);
$args = array_map('mysql_real_escape_string', $args);
array_unshift($args,$query);
$query = call_user_func_array('sprintf',$args);
$result = mysql_query($query) or die(mysql_error());
if($result){
return $result;
}else{
$error = "Error";
return $result;
}
}
//logout function
function logout(){
session_destroy();
return;
}
//check if loggedin
function logincheck($logincode, $user_table, $pass_column, $user_column){
//make sure password column and table are set
if($this->pass_column == ""){
$this->pass_column = $pass_column;
}
if($this->user_column == ""){
$this->user_column = $user_column;
}
if($this->user_table == ""){
$this->user_table = $user_table;
}
//exectue query
$result = $this->qry("SELECT * FROM ".$this->user_table." WHERE ".$this->pass_column." = '?';" , $logincode);
$rownum = mysql_num_rows($result);
//return true if logged in and false if not
if($row != "Error"){
if($rownum > 0){
return true;
}else{
return false;
}
}
}
//reset password
function passwordreset($username, $user_table, $pass_column, $user_column){
//generate new password
$newpassword = $this->createPassword();
//make sure password column and table are set
if($this->pass_column == ""){
$this->pass_column = $pass_column;
}
if($this->user_column == ""){
$this->user_column = $user_column;
}
if($this->user_table == ""){
$this->user_table = $user_table;
}
//check if encryption is used
if($this->encrypt == true){
$newpassword = md5($newpassword);
}
//update database with new password
$qry = "UPDATE ".$this->user_table." SET ".$this->pass_column."='".$newpassword."' WHERE ".$this->user_column."='".stripslashes($username)."'";
$result = mysql_query($qry) or die(mysql_error());
$to = stripslashes($username);
//some injection protection
$illigals=array("n", "r","%0A","%0D","%0a","%0d","bcc:","Content-Type","BCC:","Bcc:","Cc:","CC:","TO:","To:","cc:","to:");
$to = str_replace($illigals, "", $to);
$getemail = explode("@",$to);
//send only if there is one email
if(sizeof($getemail) > 2){
return false;
}else{
//send email
$from = $_SERVER['SERVER_NAME'];
$subject = "Password Reset: ".$_SERVER['SERVER_NAME'];
$msg = "Your new password is: ".$newpassword."
";
//now we need to set mail headers
$headers = "MIME-Version: 1.0 rn" ;
$headers .= "Content-Type: text/html; rn" ;
$headers .= "From: $from rn" ;
//now we are ready to send mail
$sent = mail($to, $subject, $msg, $headers);
if($sent){
return true;
}else{
return false;
}
}
}
//create random password with 8 alphanumerical characters
function createPassword() {
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;
while ($i <= 7) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
//login form
function loginform($formname, $formclass, $formaction){
echo'';
}
//reset password form
function resetform($formname, $formclass, $formaction){
echo'';
}
//function to install logon table
function cratetable($tablename){
$qry = "CREATE TABLE IF NOT EXISTS ".$tablename." (
userid int(11) NOT NULL auto_increment,
useremail varchar(50) NOT NULL default '',
password varchar(50) NOT NULL default '',
userlevel int(11) NOT NULL default '0',
PRIMARY KEY (userid)
)";
$result = mysql_query($qry) or die(mysql_error());
return;
}
}
Usage
This class can be used in many different scenarios, from traditional redirection to AJAX implementation.
Instantiate the Class
Make sure to include and instantiate the class on every page you use it.
include("class.login.php");
$log = new logmein(); //Instentiate the class
$log->dbconnect(); //Connect to the database
$log->encrypt = true; //set to true if password is md5 encrypted. Default is false.
Create Log on Table
Run this code only once to create the log on table.
include("class.login.php");
$log = new logmein();
$log->cratetable('logon');
Display Login Form
The login form takes in Class and ID parameters for easy styling with CSS, and form action parameter. If needed the form includes a hidden field "action" set to "log in".
include("class.login.php");
$log = new logmein();
$log->encrypt = true; //set encryption
//parameters here are (form name, form id and form action)
$log->loginform("loginformname", "loginformid", "form_action.php");
Display Password Reset Form
Just like the login form, the password reset form takes in Class, ID and form action parameters. If needed the form includes a hidden field "action" set to "resetlogin".
include("class.login.php");
$log = new logmein();
$log->encrypt = true; //set encryption
//parameters here are (form name, form id and form action)
$log->resetform("resetformname", "resetformid", "form_action.php");
Password Protect a Page
Place this code on top of every page you want to password protect.
include("class.login.php");
$log = new logmein();
$log->encrypt = true; //set encryption
//parameters are(SESSION, name of the table, name of the password field, name of the username field)
if($log->logincheck($_SESSION['loggedin'], "logon", "password", "useremail") == false){
//do something if NOT logged in. For example, redirect to login page or display message.
}else{
//do something else if logged in.
}
Login
Place this code inside the form action script. For example, in this tutorial I am using "form_action.php" as my form action script.
//instantiate if needed
include("class.login.php");
$log = new logmein();
$log->encrypt = true; //set encryption
if($_REQUEST['action'] == "login"){
if($log->login("logon", $_REQUEST['username'], $_REQUEST['password']) == true){
//do something on successful login
}else{
//do something on FAILED login
}
}
Log out
Place this code inside the script that is executed when user want's to log out.
include("class.login.php");
$log = new logmein();
$log->encrypt = true; //set encryption
//Log out
$log->logout();
//do something
Reset Password
Place this code inside the script that will run when password recovery is requested.
include("class.login.php");
$log = new logmein();
$log->encrypt = true; //set encryption
if($_REQUEST['action'] == "resetlogin"){
if($log->passwordreset($_REQUEST['username'], "logon, "password", "useremail") == true){
//do something on successful password reset
}else{
//do something on failed password reset
}
}
Download Class
Do you like this or find it useful? Drop me a note or treat me to a double-espresso from my favorite coffee shop.

Comments
November 25th 2009
nav - very useful
Reply
December 14th 2009
jagoanweb - nicee... :) is reset password similar with change password?
Emir - Not really. Reset password generates a random password. A new function would need to be added for custom password change.
Reply
December 30th 2009
chris - Will this run in mysql 4?
Emir - It should. Those are just some simple sql statements.
Reply
March 3rd 2010
kumar - hello sir, can pls send me a example created based on the above script . . i thnk u may understand wat iam asking am not getting the correct usage. . it will be help ful more if it is illustrated with example of writing.
Reply
March 3rd 2010
kumar - hello sir, can pls send me a example created based on the above script . . i thnk u may understand wat iam asking am not getting the correct usage. . it will be help ful more if it is illustrated with example of writing. my email-id is banothkumar@gmail.com i will be thankful to you. . .!!
Reply
March 6th 2010
dosen - hey man, can you provide working code in zip file in all of your posts because many of them dosn't work when they are copied of the screen.
Reply