Skip to content

PHP, MySQL, OOP Login Form Complete Example – Live Demo

Share Button

This is a complete example of a PHP MySQL Login Form.

Let’s start.

PHP, MySQL login form consists of:

Login, Password inputs & submit button
Custom Logo on top of the form
Error checking
Sessions with redirection to different page
Form Logout

php_mysql_login_form_s_shot

 

Live Demo

 

In order to start we need to create a Table that will store all login details.

CREATE DATABASE sharemyweb;

 

After a database is created, let’s create a table with some example data:

CREATE TABLE userLogin (
id INT(10) AUTO_INCREMENT PRIMARY KEY,
login VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL) 

 

 

Each time we add some new login detail, id will be auto incremented so we don’t need to do it manually.
Next we’re going to apply a MySQL class which will make MySQL connection, run login query, escape values and authenticate login & password input, close database connection.

<?php
/* Require MySQL Credentials : */
require_once("conf.php");

class MySQL{

    public $connection;

    /* Class constructor */
    function __construct() {
        $this->open_connection();
        $this->real_escape_string_exists = function_exists("mysqli_real_escape_string");    
    }

    /* Open MySQL Connection */
    public function open_connection() {
    /* Try connection */
        try {
            $this->connection = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
        }

        /* Catch Exception*/
        catch(Exception $except) {
            die("Unable to connect to Database");
        }
    }
        
    /* Run sql Query */
    public function query($sql){
        $result = mysqli_query($this->connection, $sql);         
        return $result;
    }
    
    /* Find entries by sql query */
    public function find_by_query($query=""){        
        $result=mysqli_query($this->connection,$query);        
        /* Associative array */
        $row=$this->fetch_array($result);
        return $row;
    }

    /* Fetch array and return result */
    public function fetch_array($result){
        return mysqli_fetch_array($result,MYSQLI_ASSOC);
    }
    
    /* Escape unwanted characters like slashes etc. */ 
    public function escape_value($value){
        $value = trim($value);
        /* PHP v4.3.0 or higher */
        if($this->real_escape_string_exists) {
            /* If magic quotes are active */ 
            if(get_magic_quotes_gpc()){ 
                /* Strip slashes */
                $value = stripslashes($value); 
            }
            /* Escape special characters in a string */
            $value = mysqli_real_escape_string($this->connection, $value);
        }
        else{
            // Before PHP 4.3.0
            if(!$this->magic_quotes_active){
                $value = addslashes($value);
            }
        }
        return $value;
    }
    
    /* Login authentications */
    public function authenticate($login="", $password=""){
        /* Sanitize input : Escape unwanted charactets */
        $login = $this->escape_value($login);
        $password = $this->escape_value($password);
        
        /*  Run query - Remember to put LIMIT 1 at the end of query in order to return
            only 1 row 
        */
        $sql = "SELECT login,password FROM userLogin " ;
        $sql .= "WHERE login = '{$login}' ";
        $sql .= "AND password = '{$password}' ";
        $sql .= "LIMIT 1";
        
        $result_array = $this->find_by_query($sql);
        return $result_array;
        
        /* Close connection everytime we don't need to run any more queries */
        $this->close_connection();
    }
    
    /* Close MySQL Connection */
    public function close_connection()
    {
        if(isset($this->connection))
        {
            $this->connection->close();
            unset($this->connection);
        }
    }
    
}// class End
?>

 

Remember! We’ll have to open a conf.php file and change MySQL Database credentials in order to successfully connect to database. you’ll find there a defined constant that’s awaiting your new Database detail. It looks like this:

/**
* The base configurations of MySQL settings.
*
*  Database Constrants
*  If consttants are defined : CONNECT if NOT defined :  DEFINE CONSTANTS
*
*  FILL values below! Otherwise, there'll be no Database Connection.
*/


/** MySQL Server / hostname .... optionally localhost*/
defined("DB_SERVER") ? null : define("DB_SERVER", "127.0.0.1");

/** MySQL Database to be Connect to*/
defined("DB_NAME") ? null: define("DB_NAME", "sharemyweb");

/** MySQL database username */
defined("DB_USER") ? null : define ("DB_USER", "your_DB_user");

/** MySQL database password */
defined("DB_PASSWORD") ? null : define ("DB_PASSWORD", "your_DB_password");

/** Database Charset to use in creating database tables. */
defined('DB_CHARSET') ? null : define('DB_CHARSET', 'utf8');

 

Markup  of the form is easy and straightforward so I won’t explain it that much.
You’ll see it when you download full example.

Below code shows an ValidateErrors class that will take care of input errors in the form.
You can add your own errors and call them later on during input validation.
This class in more than helpful and applies easy ways of checking and displaying errors when working with bigger form when you need to validate.
You can find another example usage of this class with some extra REGEX validation here:
LINKG TO THE POST CLASS.

<?php 
/** Simple Error Class *
* - Define Error Messages, Regular Expressions 
* - Log Errors to Error Array * - Sanitize Input 
* - Print/Display Errors 
*  Please Note that this class does it's job, but you may want to do things 
* different way or change something here & there. 
* This Class gives a Patern/shows the way, of how errors could be handled in OOP way. 
* Feel free to modify,use and reffer it anyway you want. 
*/ 

class ValidateErrors{ 

/** Error Array for all Errors Occured during Validation/Check process */ 
public $errors=array(); 

/** 
* validate_errors array stores information about Errors. 
* i.e. 'ERROR NAME' = > 'ERROR MESSAGE'
*/    
    /** Errors types - You can add your ow errors if you wish */
    protected function validationErr(){
        /* Array with error types */
        $this->validate_errors = array(
            "ERR_EMPTY_LOGIN"       =>  "Login field is empty",
            "ERR_EMPTY_PASS"        =>  "Password field is empty",
            "ERR_WRONG_DETAILS"     =>  "Wrong login or password"
        );        
        /** Return Error Array */
        return $this->validate_errors;
    }
        
    /** Logs an Error to Regular Error Array */
    public function logErrors($error){
        $this->errors["$error"] = $this->validationErr()["$error"];
    }
    
    /** Check if there are any errors in Error Array */
    public function noErrors(){
        if(empty($this->errors)){
            return true;
        } else {
            return false;
        }
    }
    
    /** If login field is empty log error to the error array */
    protected function emptyLogin($login){
        if(empty($login) || is_null($login) || !$login){
            /** Log Error to the Errors Array */
            $this->logErrors("ERR_EMPTY_LOGIN");
        }
    }
    
    /** If password field is empty log error to the error array */
    protected function emptyPass($password){
        if(empty($password) || is_null($password) || !$password){
            /** Log Error to the Errors Array */
            $this->logErrors("ERR_EMPTY_PASS");
        }
    }
        
    /** Below function check & display any number of arguments passed 
    *   Each argument should represent the key(Error) of FormErrors
    *   example use: printErrors("ERR_NO_NAME","ERR_REG_NAME")
    */
    public function printErrors(){  
        /**  Returns the number of arguments passed to the function */
        $numOfArgs = func_num_args();  
        /** Returns an array with all arguments passed to the function */   
        $listOfArgs = func_get_args();
        /** Loop through array & display results */
        for ($i = 0; $i < $numOfArgs; $i++) { if(!empty($this->errors)){
                if(array_key_exists($listOfArgs[$i],$this->errors)){
                    echo $this->errors[$listOfArgs[$i]];
                }
            }
        }
    }
    
    /** Pass functions you would like to check for a $_POST['name]/$name */
    public function checkErrors($login,$pass){
        
        /** Check for Conditions/ */
        $this->emptyLogin($login);
        $this->emptyPass($pass);
        
        /** Check for Errors in Error Array */
        if(!$this->noErrors()){
            return false;
        }else{
            return true;
        }   
    }    
} // Class End

 

After we’ve specified all errors types we would like to be displayed when occur, we can call printErrors() which specifies errors to be checked for like this:

<?php
    /* Chosen error types to be printed */
    if(isset($errors))
        $errors->printErrors("ERR_EMPTY_LOGIN","ERR_EMPTY_PASS","ERR_WRONG_DETAILS");
?>

 

Example of form with wrong input:

php_mysql_login_form_s_shot_wrong_input

 

Login & Password used withing Live Demo are:

Login:           sharemyweb

Password:   password

 

As It’s a complete login form example I’m going to show you how to make save a logged user to session.
It’s a very simple way to do so. I’ve created an authorized.php page to which we’ll be redirected after successful log in.

 

php_mysql_login_form_s_shot_authorized
After we are redirected to authorized.php page we won’t be able to go back to login page for as
long as we’re logged in.

 

Checkout Live Demo and  download full code for FREE!

Live Demo

 

Share Button