Php login logout system through ajax in jquery for beginners.

Now we will learn how to create a simple login process through Ajax with JQuery. In this example our files are the same as we used in the simple login process except we have some changes in the code.

We will create following files.

  • 1. login.php
  • 2. authenticate.php
  • 3. index.php
  • 4. logout.php
  • Please execute below SQL to create table users..

    CREATE TABLE IF NOT EXISTS `users` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `username` varchar(50) NOT NULL,
      `password` varchar(150) NOT NULL,
      `name` varchar(50) NOT NULL,
      `active` int(11) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM;
    

    Now we need to add jQuery in our login.php file, we can download and add the latest version of jQuery at the head section of our login.php file.

    1.  <head>
    2.    <script src="js/jquery-1.11.1.js"></script>
    3.  </head>
    4.  <body>
    

    Now we need to create a login form for user to provide a username and password. We will create a form with two text fields named username and password and one simple button (not submit) and we will assign a javascript function to the onclick event of this button

    Below is the code of login form.

    1.  <form method="post" id="login_form">
    2.  <table width="100%" cellpadding="4" cellspacing="0" border="0">
    3.  <tr>
    4.      <td>Username:</td>
    5.        <td><input type="text" name="username"></td>
    6.    </tr>
    7.    <tr>
    8.        <td>Password:</td>
    9.        <td><input type="password" name="password"></td>
    10.    </tr>
    11.    <tr>
    12.        <td></td>
    13.        <td><input type="button" value="Login" onclick="submit_login_form();"></td>
    14.    </tr>
    15. </table>
    16. </form>
    17. <script>
    18.     function submit_login_form() {
    19.        
    20.        var ser = $("#login_form").serialize();
    21.        $.ajax({
    22.            url: "authentiate.php",
    23.            data: ser,
    24.            type: 'POST',
    25.            dataType: 'json',
    26.            success : function(data, jqXHR) {
    27.                if(parseInt(data) == 1) {
    28.                    location.href = "index.php";
    29.                }else {
    30.                    $("#status").html("User or Password is incorrect please try again.");
    31.                }
    32.            },
    33.            
    34.        })
    35.    }
    36.    </script>
    

    At the line number 1 we are creating form tag and setting its ID attribute to login_form. This ID attribute will be used to read and submit data via Ajax to the authenticate.php file and authenticate.php file will authenticate the user.

    To show our form in tabular format we have created an Html table at line number 2.

    Line number 5 and 9 creates two form fields username and password.

    Line number 13 creates a simple button and we have assigned a javascript function submit_login_form() to it and when user will press this button the code of this function will be executed which is defined from line number 18 to 35.

    At the line number 18 we are reading form data through its id “login_form” then we are serializing this data through query standard function serialize () and at line number 23 data are being set to data variable of Ajax and at the line number 26 we are getting response from authenticate.php file. If we get 1 from authenticate.php then we redirect user to the index.php file and if we get 0 then we can show error message.

    When a user fills this form and press login button these form data get submitted to authenticate.php file via Ajax

    Below is the code of authenticate.php.

    1.  session_start();
    2.  mysql_pconnect('localhost','root','pass');
    3.  mysql_select_db('test') or die('connection error ');
    4.  if($_POST) {
    5.      $username = trim($_POST['username']);
    6.      $password = trim($_POST['password']);
    7.      if($username != '') {
    8.          $query = "select * from users where username = '$username' and active = 1";
    9.          $result = mysql_query($query)  or die(mysql_error());
    10.         $row = mysql_fetch_array($result);
    11.         if($row['password'] == $password) {
    12.             $_SESSION['user_id']  = $row['id'];
    13.             $_SESSION['username']  = $row['username'];
    14.             print 1;
    17.         }else {
    18.             print 0;
    20.         }
    21.     }
    22. }
    

    At line number 1 we are starting a session. This is required when we need to set or retrieve data from the session.

    At line number 2 we are getting connected to MySql server, we need server name, username and password to connect to the MySql server and our server name is localhost , username is the root and password is the pass.

    At line number 3 we are getting selected a database.

    Line 4 is to check that we come here from the form POST method. because code next to it should not execute when user direct type the file name authenticate.php in the browser address bar.

    On Line 5 and 6, we are storing username and password fields value in variables.

    Line 7 checks for blank username.

    At the line number 8 we are trying to get a single record where username is the submitted username and active is equal to 1 and we are not using the password field in this SQL query and checking password later on in the code. This type of process saves you from hackers SQL injection.

    At line 9,10 we are executing mysql queries and fetching record from table to check the password.

    Now at line 11 we are matching password with users submitted password. if password does match with the saved password then we are setting id and username of user in the session data. this data will be saved until user does not left the site. then we are echo 1 as a result flag. this flag will be transfer to the success function of ajax defined at line number 26.

    If password does not match then we will echo 0 as a result a this flag will be transfer to the success function of ajax.

    code for index.php

    1. session_start();
    2. if(!$_SESSION['user_id']) {
    3.     header('location:login.php');
    4.     exit;
    5. }
    6. echo 'You are now logged in <br/>';
    7. echo '<a href="logout.php">Logout</a>';
    

    When user redirected to the index.php we just show a simple message that “you are now logged in” with a logout link.

    From the line number 2 to 5 we are checking if user_id not stored is session data then user will be redirected to login.php.

    This is required to avoid executing index.php file when someone try to access index.php file directly from browser.

    Code For Logout.php

    1. session_start();
    2. unset($_SESSION['user_id']);
    3. unset($_SESSION['password']);
    4. header('location:login.php');
    5. exit;
    

    At the line number 2,3 we are unset the session data and redirecting the user to the login.php. This process will destroy session data and browser will not remember it.

Leave a Reply

Your email address will not be published. Required fields are marked *

19 − 15 =