Posted by Arjun on Wednesday 13th September 2017

Ajax Login form using PHP and MySQL

Ajax MySQL PHP Code Snippets Login PDO

Today I would like to show you Ajax login functionality implementation using PHP and MySQL. We gonna use MySQL PDO driver in this tutorial. PDO has a much nicer interface, you will end up being more productive, and write safer and cleaner code.

[caption id="attachment_5403" align="aligncenter" ] Ajax Login form using PHP and MySQL [/caption]

Create Ajax Login Form

Login Form

Create a file called login_form.php with following code.

<!DOCTYPE html>
<html lang="en">
   <head>
      <!-- Required meta tags -->
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <!-- Bootstrap CSS -->
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
   </head>
   <body>
      <div class="container">
         <div class="card" style="margin-top:10%">
            <div class="card-header">
               Login
            </div>
            <div class="card-body">
            <div id="error-msg" class="alert alert-danger" style="display:none" role="alert"></div>
               <form name="login-form" action="/login.php"  id="login-form" method="post">
                  <div class="form-group">
                     <label for="email">Email address</label>
                     <input type="email" class="form-control" name="email" id="email" placeholder="Enter email">
                  </div>
                  <div class="form-group">
                     <label for="password">Password</label>
                     <input type="password" class="form-control" name="password" id="password" placeholder="Password">
                  </div>
                  <button type="submit" id="login" class="btn btn-primary">Login</button>
               </form>
            </div>
         </div>
      </div>
      <!-- Optional JavaScript -->
      <!-- jQuery first, then Popper.js, then Bootstrap JS -->
      <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
   
      <script>
            $(function()
            {
                $('#login').click(function(e){

                    let self = $(this);

                    e.preventDefault(); // prevent default submit behavior

                    self.prop('disabled',true); 

                    var data = $('#login-form').serialize(); // get form data

                     // sending ajax request to login.php file, it will process login request and give response.
                    $.ajax({
                        url: '/login.php',
                        type: "POST",
                        data: data,
                    }).done(function(res) {
                        res = JSON.parse(res);
                        if (res['status']) // if login successful redirect user to secure.php page.
                        {
                            location.href = "secure.php"; // redirect user to secure.php location/page.
                        } else {

                            var errorMessage = '';
                            // if there is any errors convert array of errors into html string, 
                            //here we are wrapping errors into a paragraph tag.
                            console.log(res.msg);
                            $.each(res['msg'],function(index,message) {
                                errorMessage += '<p>' + message+ '</p>';
                            });
                            // place the errors inside the div#error-msg.
                            $("#error-msg").html(errorMessage);
                            $("#error-msg").show(); // show it on the browser, default state, hide
                            // remove disable attribute to the login button, 
                            //to prevent multiple form submissions 
                            //we have added this attribution on login from submit
                            self.prop('disabled',false); 
                        }
                    }).fail(function() {
                        alert("error");
                    }).always(function(){
                        self.prop('disabled',false); 
                    });
                });
            });
        </script>
   
   </body>
</html>

Database Detials

This tutorial assuming that you have following user table structure in your database. For the sake of example script, I have provided insert query with test data.

CREATE TABLE IF NOT EXISTS `users` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(255) NOT NULL,
  `last_name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`user_id`, `first_name`, `last_name`, `email`, `password`, `date_added`) VALUES
(1, 'Arjun', 'PHP', '[email protected]', '$2y$10$8mVSGv/bIGgcvCikXBPfTu7HfXMl3jqfiirtQGyRwV5bvOzNGmmLG', '2017-10-12 18:09:10');

You can generate password hash by using password_hash() function, example echo password_hash("password", PASSWORD_DEFAULT);.

Config.php

After importing above table into your database. Create a file called config.php, where you gonna save information about MySQL Data base configuration, you can use this file to save other configu

<?php
   define('DB_SERVER', 'localhost');
   define('DB_USERNAME', 'root');
   define('DB_PASSWORD', '');
   define('DB_DATABASE', 'login_demo');
   $db = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_DATABASE, DB_USERNAME, DB_PASSWORD);
?>

Login

Create a file called login.php with following code. This file will handle the login requests, It will validate user details against to the database. Upon valid and successful login, it will start the user session, otherwise, it will throw the appropriate error message.

  <?php
  require_once('config.php');

   $error  = array();
   $res    = array();

        
        if(empty($_POST['email']))
        {
            $error[] = "Email field is required";    
        }
    
        if(empty($_POST['password']))
        {
            $error[] = "Password field is required";    
        }
        if (!empty($_POST['email']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
            $error[] = "Enter Valid Email address";
        } 
         
        if(count($error)>0)
        {
            $resp['msg']    = $error;
            $resp['status'] = false;    
            echo json_encode($resp);
            exit;
        }

        $statement = $db->prepare("select * from users where email = :email" );
        $statement->execute(array(':email' => $_POST['email']));
        $row = $statement->fetchAll(PDO::FETCH_ASSOC);
        if(count($row)>0) {
           if(!password_verify($_POST['password'],$row[0]['password'])) {
                $error[] = "Password is not valid";
                $resp['msg']  = $error;
                $resp['status']   = false;    
                echo json_encode($resp);
                exit; 
           }
          session_start();
          $_SESSION['user_id'] = $row[0]['user_id'];
          $resp['redirect']    = "dashboard.php";
          $resp['status']      = true;    
          echo json_encode($resp);
          exit;    
       } else {
          $error[] = "Email does not match";
          $resp['msg']  = $error;
          $resp['status']   = false;    
          echo json_encode($resp);
          exit;    
     } 

secure.php

Create a file called secure.phpfile with following code. On successful login we will redirect user to this page. Only authenticated user can access this page. If unauthorized users try to access this page, users will forcefully redirected to login page.

<?php
session_start();
if(empty($_SESSION['user_id'])){
   header('location: login_form.php');    
} else {
   echo 'Secure page!.';
   echo '<a href="/logout.php">logout</a>';
}

logout.php

Create a file called logout.php file and put below code in the file.

session_start(); 
session_destroy(); 
header('location: login.php');

Once everything is in place head over to the browser with http://localhost/login_form.php you should get output something like below image
[caption id="attachment_5409" align="aligncenter" width="1191"]Ajax Login form using PHP and MySQL Ajax Login form using PHP and MySQL
[/caption]