PHP Login Script Using MySQLi JQuery And Ajax

Login is most important feature for our application . Hacker can easily hack your website if you make simple login mechanism in our application . In this tutorial i will show you how to do strong user authentication mechanism using php and mysqli. It is pretty simple and easy. I am going to create this mechanism using oop php and jquery along with ajax . Here i will show you php secure login script and i will use hashing not MD5 system.  php secure login script 

login-form-in-php-with-ajax

In this tutorial we will know how to validate form using php ajax and jquery. So let's start login and registration form in php using ajax tutorial.

CONNECT DATABASE

To connect database first create a config.php file. Write those following code to this file.

define(“DB_HOST”, “localhost”);
define(“DB_USER”, “root”);
define(“DB_PASS”, “”);
define(“DB_NAME”, “db_login”);

 

Then create a file name will be Database.php asd write those following code to this file

Class Database{
    public $host = DB_HOST;
    public $user = DB_USER;
    public $pass = DB_PASS;
    public $dbname = DB_NAME;
        
    public $link;
    public $error;
        
    public function __construct(){
       $this->connectDB();
    }

    private function connectDB(){

    $this->link = new mysqli($this->host, $this->user, $this->pass, $this->dbname);
    
      if(!$this->link){
      $this->error =”Connection fail”.$this->link->connect_error;
     return false;
      }
    }

    public function select($query){

       $result = $this->link->query($query) or die($this->link->error.__LINE__);
        if($result->num_rows > 0){
         return $result;
         } else {
         return false;
        }
       }
    }

 

Creating the Database Table

CREATE TABLE tbl_user(
   id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
   email VARCHAR(50) NOT NULL UNIQUE,
   password VARCHAR(255) NOT NULL,
   created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

 

As we are going to create Login system that’s why we have to work with Session. So create a file whose name will be Session.php and paste those following code into this file .

    class Session
    {
    public static function init(){
      session_start();
    }

    public static function set($key,$value){
        $_SESSION[$key] = $value;
    }

    public static function get($key){
       if (isset($_SESSION[$key])){
        $result = $_SESSION[$key];
    }

    if (isset($result)) {
        return $result;
    }else{
      return false;
     }
    }

    public static function checkSession(){
       self::init();
       if(self::get(“login”) == false){
        self::destroy();
       header(“Location:login.php”);
      }
    }

    public static function checkLogin(){
       self::init();
       if(self::get(“login”) == true){
       header(“Location:index.php”);
      }
    }

    public static function destroy(){
       session_destroy();
       header(“Location:login.php”);
     }
    }

 

Look here we declared all method static . If you don’t know how to work with static method then see this following tutorial .How to work with static method .

Now our setup is done . Now we have to do our next step . Create a file whose name will be login.php and paste those code into this file.

 

Creating Function.js File

Now create a file whose name will be function.js and paste those code into this file

$(document).ready(function () {
    $(“#submit”).click(function () {
        var email = $(“#email”).val();
        var password = $(“#password”).val();
        if (email.length == “” || password.length == “”){
        $(“#message”).html(“please fill out this field first”).fadeIn();
        $(“#message”).addClass(“error”);
        return false;
    }else {
        $.ajax({
            type: ‘POST’,
            url: ‘redirect.php’,
            data: { email: email, password: password },
            success: function (feedback) {
                $(“#text”).html(feedback);
            }
        });
    }
});
$(“.email_error_text”).hide();
$(“.password_error_text”).hide();
var error_email = false;
var error_password = false;
$(“#email”).focusout(function () {
    check_email();
});
$(“#password”).focusout(function () {
    check_password();
});
function check_email() {
    $(“#message”).hide();
    var pattern = new RegExp(/^([a-zA-Z0–9_\.\-])+\@(([a-zA-Z0–9\-])+\.)+([a-zA-Z0–9]{2,4})+$/);
    if (pattern.test($(“#email”).val())) {
        $(“.email_error_text”).hide();
    } else {
        $(“.email_error_text”).html(“Invalid email address”);
        $(“.email_error_text”).show().addClass(“error”);
        error_email = true;
    }
}
function check_password() {
    $(“#message”).hide();
    var password_length = $(“#password”).val().length;
    if (password_length < 8) {
        $(“.password_error_text”).html(“Should be at least 8 characters”);
        $(“.password_error_text”).show().addClass(“error”);
        error_password = true;
    } else {
        $(“.password_error_text”).hide();
    }
}
    });

 

Now finally create our redirect.php file and paste those code into this file and see below code

 include ‘config.php’;
    include ‘Database.php’;
    include ‘Session.php’;
    $db = new Database();

    if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {

    $email = $_POST[‘email’];
    $password = $_POST[‘password ‘]
    $email = strip_tags(mysqli_real_escape_string($db->link,trim($email)));
    $password = strip_tags(mysqli_real_escape_string($db->link,trim($password)));

    $query = “SELECT * FROM tbl_user WHERE email = ‘$email ‘“;
    $result = $db->select($query);

    if(mysqli_num_rows($result) > 0) {

    //Now email is matched we also need to verify password

    $data = mysqli_fetch_array($result);
    $password_hash = $data[‘password’];
    if ( password_verify($password ,$password_hash)) { 

    //Make sure when you will create registration mechanism where you have to insert password using password_hash() function .
    //If we are here it means password is verified , So we can redirect user

    Session::set(“userId”, $data[‘id’]); 
      //catching user id by Session
        echo “window.location = ‘index.php’;”; //Use script tag and close also
      }
    else{
        echo “Password is not matched”;
      }
    }
    else{
        echo “alert(‘Email is not matched’);”; //Use script tag and close also
     }
    }

 

SIGN OUT

Now we are going to create log out option. Now go to your sign out or log out button where you have created it. And do which i have done below

 

Now just write the following code in your header.php file.

include ‘Session.php’;
  Session::checkSession(); //Checking Session whether user logged in or not
  if (isset($_GET[‘action’]) && $_GET[‘action’] == “logout”) {
    Session::destroy();
  exit();
}

 

Hope the total procedure you will understand . Here keep in mind that , if a user is not logged in , then user can’t access your index.php page. This theory you can use if you developed an admin panel. If you want they can access in index page without login then just remove this code

 

Read also : How to create class and object in php

 

include ‘Session.php’;
Session::checkSession(); //Checking Session whether user logged in or not

 

Hope you will understand all these procedure that how to login through ajax.

 

#php #mysqli #ajax #jquery