Surfe.be - passive income

PHP Login Script With MySQL and Ajax

Login PHP with MySQL 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 .

Before starting our project first you have to go to your localhost phpmyadmin to create our project Database whose name will be db_login. Also create a table whose name will be tbl_user along with three filed , one is email and other is password. 

Why Password Matter for Secuired Login

Cybersecurity experts make the recommendation for strong, unique passwords for several reasons - the first being that every day malicious cyber threat actors compromise websites and online accounts, and post lists of usernames, email addresses, and passwords online. This exposes people’s passwords, and worse yet, they are exposed with information that uniquely identifies the user, such as an email address. That means that a malicious actor can look for other accounts associated with that same person, such as work-related, personal social media, or banking accounts. When the malicious actor finds those accounts they can try logging in with the exposed password and if the password is reused, they can gain access. This is why unique passwords matter. for more visit

php login with mysql and ajax

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 PHP Login Form

<?php include 'Session.php';
     Session::checkLogin();  // Checking whether user is logged in or not.
?>

<h2>User Login - laramust.com</h2>
    <p id="text"></p>
    <p id="message"></p>

    <form action="redirect.php" method="post">
       <table>

        <tr>
         <input type="email" id="email" placeholder="Enter email" name="email">
         <span> <p class="email_error_text"></p></span>
        </tr>

      <tr>
        <input type="password" id="password" placeholder="Enter password" name="password">
        <span> <p class="password_error_text"></p></span>
      </tr>

     <tr>

        <input type="submit" id="submit" value="Submit" style="margin-top: 5px;">
     </tr>

      </table>
   </form>

Make sure you have to add those below code in login.php page .

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="function.js"></script>

 <style type="text/css">
   .error{
	color:red;
       font-size: 20px;
	}
 </style>

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

Redirect.php

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 "<script> window.location = 'index.php'; </script>";
            }
             else{
               echo "<span style='color:red; font-size:18px;'> Password is not matched </span>";
            }
         }
         else{
            echo "<script> alert('Email is not matched');</script>";
         }
  }

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

<a href="?action=logout" class="btn btn-default btn-flat">Sign out</a>

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

<?php
      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 he 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 

<?php include 'Session.php';
      Session::checkSession(); //Checking Session whether user logged in or not
?>

Hope you will understand all these procedure. If you like this tutorial please leave a comments and share with your friends. If you find any error of this tutorial , please share this with me.

Leave a comments

LET'S SOCIALITE

Recent Tweets

RECOMMENDED POST