PHP-based AJAX implementation without flush login and exit

Source: Internet
Author: User
Tags echo date md5 encryption jquery library
This article improves the user experience by using AJAX no-flush login and exit. If the user is logged in, the user-related login information is displayed, otherwise the login form is displayed.

User login and exit features are applied in many places, and in some projects, we need to use Ajax to log in, only refresh the page after successful login, thereby enhancing the user experience. This article will use PHP and jquery to implement login and logout functions.

Prepare 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 (ten) default NULL COMMENT ' login time ',  ' login_ip ' varchar (3 2) default NULL COMMENT ' login IP ',  ' login_counts ' int (ten) not NULL default ' 0 ' COMMENT ' login number ',  PRIMARY KEY (' id ')) E Ngine=myisam DEFAULT Charset=utf8;

Then insert a user information data into the users table:

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

index.php

The user enters the user name and password, prompts the user to log in successfully, and displays the relevant login information, if you click "Exit", then exit to the user login screen.
Enter index.php, if the user is logged in displays the login information, if not logged in the Display login box requires the user to log in.

<p id= "Login" > 

Note that the index.php file header should be added with the statement: session_start; You can also write a nice CSS style for the login box by introducing the jquery library in the head section as well as the global.js, and of course This example has 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 let the input box to get the focus, like Baidu and Google as soon as the open, the mouse cursor in the input box. Use the following code:

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

The next thing to do is to render different styles when the input box gets and loses focus, such as using a different border color in this example, with the following code:

$ ("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 the login button, first to verify that the user's input cannot be empty, and then send an AJAX request to the background login.php. When the background verifies that the login is successful, the logged-on user information is returned, such as the number of user logins and the last logon time, and the logon failure information if the login fails.

$ (". Btn"). Live (' click ', function () {var user = $ ("#user"). Val ();   var pass = $ ("#pass"). Val (); if (user== "") {$ (' <p id= "msg"/> '). html ("User name cannot be empty!     "). AppendTo ('. Sub '). FadeOut (2000);     $ ("#user"). focus ();   return false; } if (pass== "") {$ (' <p 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 }, Beforesend:function () {$ (' <p id= "msg"/> '). AddClass ("Loading"). HTML ("Logging in ..."). CSS ("Color", "#999"). AP     Pendto ('. Sub ');         }, Success:function (JSON) {if (json.success==1) {$ ("#login_form"). Remove (); var p = "<p id= ' result ' ><p><strong>" +json.user+ "&LT;/STRONG&GT; Congratulations on your successful login! </p> <p> You This is the section <span> "+json.login_counts+" </span> times login to this site. </p> <p> The last time you logged in to this site is:<span> "+json.login_time+" </span></p><p> <a href= ' # ' id= ' logout ' > ' exit </a></p></p> ';       $ ("#login"). Append (P);         }else{$ ("#msg"). Remove ();         $ (' <p id= ' errmsg "/> '). html (json.msg). CSS (" Color "," #999 "). AppendTo ('. Sub '). FadeOut (2000);       return false; }     }   }); });

When I am making an AJAX request, the data transfer format uses JSON, the return is JSON data, using JS to parse the JSON data, get the user information after login, and then append to the #login element via append to complete the login operation.
User exit: When clicking "Exit", send an AJAX request to login.php, log off all session, the page back to the login screen.

$ ("#logout"). Live (' click ', Function () {   $.post ("Login.php?action=logout", Function (msg) {     if (msg==1) {        $ ("#result"). Remove ();        var p = "<p id= ' login_form ' ><p><label> user name:</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>        <p class= ' Sub ' ><input type= ' submit ' class= ' btn ' value= ' login '/ ></p>        </p> ";        $ ("#login"). Append (P);     }   }); });

login.php

Depending on the request submitted by the foreground, the user name and password entered by the user are obtained and compared with the corresponding user name and password in the database, if the match succeeds, the user login information is updated and the JSON data is assembled 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 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 error!   '; } Echo Json_encode ($arr);   Output JSON data} elseif ($action = = ' logout ') {//exit unset ($_session);   Session_destroy (); echo ' 1 '; }

The current station request exits, simply log off the session can be, and return 1 to the foreground JS processing. Note that the above code in GET_CLIENT_IP () is a function to obtain the client IP, limited to the length of the list, you can download the source code to view.

Well, a complete set of user login and exit procedures to complete, the shortcomings are unavoidable, we welcome criticism.

Summary : The above is the entire content of this article, I hope to be able to help you learn.

Related recommendations:

The role of type hints in PHP and how to use them

PHP implementation of image watermark based on the dynamic adding function of color environment

How to implement Multithreading in PHP

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.