Simple PHP/MySQL authentication/login class

Here is a simple PHP/MySQL authentication/login 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.

<?php
//For security reasons, don't display any errors or warnings. Comment out in DEV.
error_reporting(0);
//start session
session_start();
class logmein {
    //database setup
       //MAKE SURE TO FILL IN DATABASE INFO
    var $hostname_logon = 'localhost';      //Database server LOCATION
    var $database_logon = '';       //Database NAME
    var $username_logon = '';       //Database USERNAME
    var $password_logon = '';       //Database PASSWORD

    //table fields
    var $user_table = 'logon';          //Users table name
    var $user_column = 'useremail';     //USERNAME column (value MUST be valid email)
    var $pass_column = 'password';      //PASSWORD column
    var $user_level = 'userlevel';      //(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){
        //conect to DB
        $this->dbconnect();
        //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){
        //conect to DB
        $this->dbconnect();
        //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){
        //conect to DB
        $this->dbconnect();
        //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_db = md5($newpassword);
        }else{
			$newpassword_db	= $newpassword;
		}

        //update database with new password
        $qry = "UPDATE ".$this->user_table." SET ".$this->pass_column."='".$newpassword_db."' WHERE ".$this->user_column."='".stripslashes($username)."'";
        $result = mysql_query($qry) or die(mysql_error());

        $to = stripslashes($username);
        //some injection protection
        $illegals=array("%0A","%0D","%0a","%0d","bcc:","Content-Type","BCC:","Bcc:","Cc:","CC:","TO:","To:","cc:","to:");
        $to = str_replace($illegals, "", $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; \r\n" ;
            $headers .= "From: $from  \r\n" ;

            //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){
        //conect to DB
        $this->dbconnect();
        echo'
<form name="'.$formname.'" method="post" id="'.$formname.'" class="'.$formclass.'" enctype="application/x-www-form-urlencoded" action="'.$formaction.'">
<div><label for="username">Username</label>
<input name="username" id="username" type="text"></div>
<div><label for="password">Password</label>
<input name="password" id="password" type="password"></div>
<input name="action" id="action" value="login" type="hidden">
<div>
<input name="submit" id="submit" value="Login" type="submit"></div>
</form>

';
    }
    //reset password form
    function resetform($formname, $formclass, $formaction){
        //conect to DB
        $this->dbconnect();
        echo'
<form name="'.$formname.'" method="post" id="'.$formname.'" class="'.$formclass.'" enctype="application/x-www-form-urlencoded" action="'.$formaction.'">
<div><label for="username">Username</label>
<input name="username" id="username" type="text"></div>
<input name="action" id="action" value="resetlogin" type="hidden">
<div>
<input name="submit" id="submit" value="Reset Password" type="submit"></div>
</form>

';
    }
    //function to install logon table
    function cratetable($tablename){
        //conect to DB
        $this->dbconnect();
        $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 script? Download packaged file to support any future updates to it:

Related Posts: