Php+jquery+ajax Implement user Login and exit _php instance

Source: Internet
Author: User
Tags border color echo date md5 md5 encryption jquery library

User login and Exit functions are used in many places, and in some projects, we need to use Ajax way to log in, the successful login only refresh the page part, thereby enhancing the user experience. This article will use PHP and jquery to implement login and exit capabilities.

Preparing the Database

In this example we use the MySQL database to create a user table with the following table structure:

CREATE TABLE ' user ' ( 
 ' id ' int (one) not null auto_increment, 
 ' username ' varchar ' (=) NOT null COMMENT ' username ', 
 ' PA ssWOrd ' varchar NOT null COMMENT ' password ', 
 ' login_time ' int (a) default NULL COMMENT ' logon time ', 
 ' login_ip ' varchar (3 2) default NULL COMMENT ' logon IP ', 
 ' login_counts ' int (ten) NOT null default ' 0 ' COMMENT ' logon Times ', 
 PRIMARY KEY (' id ') 
   
     Engine=myisam DEFAULT Charset=utf8; 

   

Then insert a user information data into the user table:

INSERT into ' user ' (' id ', ' username ', ' password ', ' login_time ', ' login_ip ', ' login_counts ') 
 VALUES (1, ' demo ', ' fe01ce2a7fbac8fafaed7c982a04e229 ', ', ', ', 0; 

index.php

The user prompts the user for a successful login after entering the username and password, displays the relevant login information, and exits to the user login interface if you click "Exit". The
enters index.php, displays the login information if the user is logged in, and displays the login box to require the user to log in if they are not logged in.

<div id= "Login" >  

Note that the index.php file header should be preceded by a statement: session_start; Also introduce the jquery library in the Head section, and include Global.js, you can also write a beautiful CSS style for the login box, of course, this example has slightly written a simple style, please check the source code.

<script type= "Text/javascript" src= "js/jquery.js" ></script> 
<script type= "Text/javascript" src= "Js/global.js" ></script> 

Global.js

The Global.js file includes the jquery code that will be implemented. The first thing to do is to get the focus of the input box, like Baidu and Google as an open, the mouse cursor in the input box. Use the following code:

$ (function () { 
  $ (' #user '). focus (); 
}); 

The next thing to do is, when the input box gets and loses focus, it presents a different style, such as using a different border color in this example, and the code is as follows:

$ ("Input:text,textarea,input:password"). focus (function () { 
  $ (this). addclass ("Cur_select"); 
}); 
$ ("Input:text,textarea,input:password"). blur (function () { 
  $ (this). Removeclass ("Cur_select"); 
}); 

User login: After the user clicks on the login button, first verify that the user's input cannot be null, and then send an AJAX request to the background login.php. Returns the logon user information, such as the number of user logons and the last logon time, when the background verification login succeeds, and returns the login failure information if the login fails.

$ (". Btn"). Live (' click ', function () {var user = $ ("#user"). Val (); 
  var pass = $ ("#pass"). Val (); if (user== "") {$ (' <div id= ' msg '/> '). html ("User name cannot be empty!") 
    "). Appendto ('. Sub '). fadeout (2000); 
    $ ("#user"). focus (); 
  return false; } if (pass== "") {$ (' <div id= ' msg '/> '). HTML ("Password cannot be empty!") 
    "). Appendto ('. Sub '). fadeout (2000); 
    $ ("#pass"). focus (); 
  return false; } $.ajax ({type: "POST", url: "Login.php?action=login", DataType: "JSON", data: {"user": User, "Pass" :p Ass}, Beforesend:function () {$ (' <div id= ' msg '/> '). AddClass ("Loading"). HTML ("Login ..."). CSS ("Color", "# 
    999 "). Appendto ('. Sub '); 
        }, Success:function (JSON) {if (json.success==1) {$ ("#login_form"). Remove (); var div = "<div id= ' result ' ><p><strong>" +json.user+ "&LT;/STRONG&GT; Congratulations on your login success! </p> <p> You This is the first <span> "+json.login_counts+" </span> times login This site. </p> <p> The last time you logged in this site is: <spaN> "+json.login_time+" </span></p><p> <a href= ' # ' id= ' logout ' > ' exit ' &LT;/A&GT;&LT;/P&GT;&L 
        T;/div> "; 
      $ ("#login"). Append (div); 
        }else{$ ("#msg"). Remove (); 
        $ (' <div id= ' errmsg '/> '). html (json.msg). CSS ("Color", "#999"). Appendto ('. Sub '). fadeout (2000); 
      return false; 
} 
    } 
  }); 
 });

I am in the AJAX request, data transmission format using JSON, the returned data is JSON data, use JS to parse the JSON data, get the user information after login, and then through the append appended to the #login element, complete the login operation.
User exits: When the "Exit" is clicked, send an AJAX request to login.php, log back all sessions in the background, and the page returns to the login interface.

$ ("#logout"). Live (' click ', Function () { 
  $.post ("Login.php?action=logout", Function (msg) { 
    if (msg==1) { 
       $ ("#result"). Remove (); 
       var div = "<div id= ' login_form ' ><p><label> username:</label> 
       <input type= ' text ' class= ' Input ' name= ' user ' id= ' user '/></p> 
       <p><label> password:</label> <input type= ' password ' class= ' input ' name= ' pass ' 
id= ' pass '/></p> 
       <div class= ' Sub ' ><input type= ' submit ' class= ' BTN ' value= ' login '/></div> 
       </div> '; 
       $ ("#login"). Append (div);}}); 
 

login.php

According to the request submitted by the foreground, when logged in, get the user entered username and password, and match the corresponding username and password in the database, if successful, the new update the user login information, and assemble the JSON data to the foreground.

Session_Start (); 
 
Require_once (' connect.php '); 
$action = $_get[' action ']; 
  if ($action = = ' Login ') {//Login $user = stripslashes (Trim ($_post[' user ')); 
  $pass = Stripslashes (Trim ($_post[' pass ')); 
    if (Emptyempty ($user)) {echo ' username cannot be empty '; 
  Exit 
    } if (Emptyempty ($pass)) {echo ' Password cannot be empty '; 
  Exit $MD 5pass = MD5 ($pass); 
 
  The password uses MD5 encryption $query = mysql_query ("SELECT * from user where username= ' $user '"); 
 
  $US = Is_array ($row = mysql_fetch_array ($query)); $ps = $US? 
  $MD 5pass = = $row [' Password ']: FALSE; 
    if ($ps) {$counts = $row [' login_counts '] + 1; 
    $_session[' user ' = $row [' username ']; 
    $_session[' login_time ' = $row [' Login_time ']; 
    $_session[' login_counts ' = $counts; $ip = Get_client_ip (); 
    Get the login IP $logintime = mktime (); 
    $rs = mysql_query ("Update user set Login_time= ' $logintime ', login_ip= ' $ip ', login_counts= ' $counts '"); 
      if ($rs) {$arr [' success '] = 1; $arr [' msg '] = ' Login successful! 
      '; $arr[' user '] = $_session[' user ']; 
      $arr [' login_time '] = Date (' y-m-d h:i:s ', $_session[' login_time ')); 
    $arr [' login_counts '] = $_session[' login_counts ']; 
      else {$arr [' success '] = 0; 
    $arr [' msg '] = ' login failed '; 
    } else {$arr [' success '] = 0; $arr [' msg '] = ' username or password is wrong! 
  '; echo Json_encode ($arr); 
  Output JSON data} elseif ($action = = ' logout ') {//exit unset ($_session); 
  Session_destroy (); 
echo ' 1 '; 
 }

When the current request exits, just log off the session and return 1 to the front desk JS for processing. Note that the above code GET_CLIENT_IP () is to obtain the client IP function, limited to the length of the list, you can download the source code view.

Well, a complete set of user login and exit procedures completed, the deficiencies are inevitable, welcome to criticize correct.

The above mentioned is the entire content of this article, I hope you can enjoy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.