Php+jquery+ajax Implementing User Login and Exit _php tutorial

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

Php+jquery+ajax Implement user Login and exit


  Php+jquery+ajax Implement user Login and exit

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:

?

1

2

3

4

5

6

7

8

9

CREATE TABLE ' user ' (

' id ' int (one) not NULL auto_increment,

' username ' varchar (+) not NULL COMMENT ' user name ',

' Password ' varchar (+) not NULL COMMENT ' password ',

' Login_time ' int (ten) default NULL COMMENT ' login time ',

' login_ip ' varchar (+) default NULL COMMENT ' login IP ',

' Login_counts ' int (ten) not NULL default ' 0 ' COMMENT ' login count ',

PRIMARY KEY (' id ')

) Engine=myisam DEFAULT Charset=utf8;

Then insert a user information data into the users table:

?

1

2

INSERT into ' user ' (' id ', ' username ', ' password ', ' login_time ', ' login_ip ', ' login_counts ')

VALUES (1, ' demo ', ' fe01ce2a7fbac8fafaed7c982a04e229 ', ' ', ', ' 0 ');

index.php

After entering the user name and password, the user prompts the user to log in successfully and displays the relevant login information, and if you click "Exit", you will be logged out to the user login screen.

Enter index.php, if the user is logged in to display the login information, if not logged in the Display login box requires the user to log in.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21st

22

User Login

if (Isset ($_session[' user ')) {

?>

, congratulations on your successful login!

This is The first time you have logged on to this site.

The last time you landed on this site is:

Exit

User name:

Password:

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.

?

1

2

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:

?

1

2

3

$ (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:

?

1

2

3

4

5

6

$ ("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.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21st

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

$ (". Btn"). Live (' click ', function () {

var user = $ ("#user"). Val ();

var pass = $ ("#pass"). Val ();

if (user== "") {

$ ('). HTML ("User name cannot be empty!") "). AppendTo ('. Sub '). FadeOut (2000);

$ ("#user"). focus ();

return false;

}

if (pass== "") {

$ ('). 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 () {

$ ("). AddClass (" Loading "). HTML (" Logging in ... "). CSS (" Color "," #999 ")

. AppendTo ('. Sub ');

},

Success:function (JSON) {

if (json.success==1) {

$ ("#login_form"). Remove ();

var div = "

"+json.user+", congratulations on your successful login!

You this is the first "+json.login_counts+" login to this site.

The last time to log on to this site is:"+json.login_time+"

Exit

";

$ ("#login"). Append (div);

}else{

$ ("#msg"). Remove ();

$ ('). 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.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

$ ("#logout"). Live (' click ', function () {

$.post ("Login.php?action=logout", Function (msg) {

if (msg==1) {

$ ("#result"). Remove ();

var div = "

User name:

Password:< p="">

Id= ' Pass '/>

";

$ ("#login"). Append (div);

}

});

});

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.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21st

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

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 ' User name cannot be empty ';

Exit

}

if (Emptyempty ($pass)) {

echo ' Password cannot be empty ';

Exit

}

$MD 5pass = MD5 ($pass); Password using 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.

The above mentioned is the whole content of this article, I hope you can like.

http://www.bkjia.com/PHPjc/990986.html www.bkjia.com true http://www.bkjia.com/PHPjc/990986.html techarticle php+jquery+ajax Implement User login and exit Php+jquery+ajax implement user login and exit this article uses AJAX without flush login and exit, thereby enhancing the user experience. If the user is logged in status ...

  • 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.