php ajax user login and exit_PHP tutorial

WBOY
Release: 2016-07-13 16:55:10
Original
955 people have browsed it

This article mainly talks about the combination of ajax and php in jquery to achieve the user login effect without refreshing. Friends in need can refer to it.

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

The code is as follows Copy code
 代码如下 复制代码

CREATE TABLE `user` (
  `id` int(11) NOT NULL auto_increment,
  `username` varchar(30) NOT NULL COMMENT '用户名',
  `password` varchar(32) NOT NULL COMMENT '密码',
  `login_time` int(10) default NULL COMMENT '登录时间',
  `login_ip` varchar(32) default NULL COMMENT '登录IP',
  `login_counts` int(10) NOT NULL default '0' COMMENT '登录次数',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
然后往user表中插入一条用户信息数据:

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

CREATE TABLE `user` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(30) NOT NULL COMMENT 'username',
`password` varchar(32) NOT NULL COMMENT 'password',
`login_time` int(10) default NULL COMMENT 'login time',
`login_ip` varchar(32) default NULL COMMENT 'Login IP',
`login_counts` int(10) NOT NULL default '0' COMMENT 'number of logins',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Then insert a piece of user information data into the user table:

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

After the user enters the user name and password, the user will be prompted to log in successfully and the relevant login information will be displayed. If the user clicks "Exit", the user will exit to the user login interface.
 代码如下 复制代码


     

用户登录


      if(isset($_SESSION['user'])){
?>
     

       

,恭喜您登录成功!


       

您这是第次登录本站。


       

上次登陆本站的时间是:

【退出】


     

     
     

         


         



         

             
         

     

     

Enter index.php. If the user is logged in, the login information will be displayed. If the user is not logged in, the login box will be displayed to ask the user to log in.
The code is as follows Copy code

User login


                 If(isset($_SESSION['user'])){
?>

& Lt; p & gt; & lt; strong & gt; & lt;? Php echo $ _Session ['user'];? & Gt; & lt;/strong & gt;, congratulations!


& Lt; p & gt; you are the & lt; span & gt; & lt;? Php echo $ _Session ['login_counts'];? & Gt; & lt;/span & gt;


& Lt; p & gt; the time to log in to this site is: & lt; span & gt; & lt;? PHP Echo date ('y-m-d h: s', $ _ session ['login_time']);? & Gt;

【Exit】




       


         



                                                                                                                       
                                                                                                       


Note that the statement should be added to the index.php file header: session_start; at the same time, introduce the jquery library in the head part and include global.js. You can also write a beautiful CSS style for the login box. Of course, this example has been slightly written Made a simple style, please view the source code.

The code is as follows Copy code
 代码如下 复制代码


 


The global.js file includes the jquery code to be implemented. The first thing to do is to let the input box get the focus. As soon as it is opened like Baidu and Google, the mouse cursor will be in the input box. The usage 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");
});

The code is as follows Copy 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, it must first verify that the user's input cannot be empty, and then send an Ajax request to the background login.php. When the background verification login is successful, the logged-in user information is returned: such as the number of user logins and the last login time; if the login fails, login failure information is returned.

The code is as follows Copy code
$(".btn").live( 'click',function(){
 代码如下 复制代码
$(".btn").live('click',function(){
    var user = $("#user").val();
    var pass = $("#pass").val();
    if(user==""){
        $('
').html("用户名不能为空!").appendTo('.sub').fadeOut(2000);
        $("#user").focus();
        return false;
    }
    if(pass==""){
        $('
').html("密码不能为空!").appendTo('.sub').fadeOut(2000);
        $("#pass").focus();
        return false;
    }
    $.ajax({
        type: "POST",
        url: "login.php?action=login",
        dataType: "json",
        data: {"user":user,"pass":pass},
        beforeSend: function(){
            $('
').addClass("loading").html("正在登录...").css("color","#999")
.appendTo('.sub');
        },
        success: function(json){
            if(json.success==1){
                $("#login_form").remove();
                var div = "

"+json.user+",恭喜您登录成功!


               

您这是第"+json.login_counts+"次登录本站。


               

上次登录本站的时间是:"+json.login_time+"


                【退出】

";
                $("#login").append(div);
            }else{
                $("#msg").remove();
                $('
').html(json.msg).css("color","#999").appendTo('.sub')
.fadeOut(2000);
                return false;
            }
        }
    });
});
var user = $("#user").val(); var pass = $("#pass").val(); If(user==""){             $('
').html("Username 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":pass},          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!

                                                                                                                                                                                                                   

This is the "+json.login_counts+"time to log in to this site.

& Lt; p & gt; the time to log in to this site is: & lt; span & gt; "+json.login_time+" & lt;/span & lt;/p & gt; & lt;                                                                                                                                                                                                                                 $("#login").append(div);                }else{                      $("#msg").remove(); $('
').html(json.msg).css("color","#999").appendTo('.sub') .fadeOut(2000);                       return false;                                                                        } }); });

When I make an Ajax request, the data transmission format is json, and the returned data is also json data. I use JS to parse the json data to get the user information after login, and then append it to the #login element through append to complete. Login operation.

User exits
When "Exit" is clicked, an Ajax request is sent to login.php, all Sessions are logged out in the background, and the page returns to the login interface.

The code is as follows Copy code
 代码如下 复制代码

$("#logout").live('click',function(){
    $.post("login.php?action=logout",function(msg){
        if(msg==1){
             $("#result").remove();
             var div = "

 
            


            

id='pass' />


            

            
";
             $("#login").append(div);
        }
    });
});

$("#logout").live('click',function(){ $.post("login.php?action=logout",function(msg){ If(msg==1){                  $("#result").remove();                  var div = "

                 

                                                                                                                                                                                                                                                    out out out there out       through id='pass' />

                 
                                  
";                   $("#login").append(div);           } }); });

login.php
According to the request submitted by the front desk, when logging in, 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 comparison is successful, the user's login information will be newly updated and the json data transmission will be assembled. Give it to the front desk.

$action = $_GET['action']; if ($action == 'login') { //Log in
The code is as follows
 代码如下 复制代码
session_start();
require_once ('connect.php');
 
$action = $_GET['action'];
if ($action == 'login') {  //登录
    $user = stripslashes(trim($_POST['user']));
    $pass = stripslashes(trim($_POST['pass']));
    if (empty ($user)) {
        echo '用户名不能为空';
        exit;
    }
    if (empty ($pass)) {
        echo '密码不能为空';
        exit;
    }
    $md5pass = md5($pass); //密码使用md5加密
    $query = mysql_query("select * from user where username='$user'");
 
    $us = is_array($row = mysql_fetch_array($query));
 
    $ps = $us ? $md5pass == $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(); //获取登录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'] = '登录成功!';
            $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'] = '登录失败';
        }
    } else {
        $arr['success'] = 0;
        $arr['msg'] = '用户名或密码错误!';
    }
    echo json_encode($arr); //输出json数据
}
elseif ($action == 'logout') {  //退出
    unset($_SESSION);
    session_destroy();
    echo '1';
}
Copy code

session_start();

require_once ('connect.php');

$user = stripslashes(trim($_POST['user'])); $pass = stripslashes(trim($_POST['pass']));

If (empty ($user)) {

echo 'Username cannot be empty'; } If (empty ($pass)) { echo 'Password cannot be empty'; exit; } $md5pass = md5($pass); //The password is encrypted using md5 $query = mysql_query("select * from user where username='$user'"); $us = is_array($row = mysql_fetch_array($query)); $ps = $us ? $md5pass == $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 is wrong! '; } Echo json_encode($arr); //Output json data } elseif ($action == 'logout') { //Exit Unset($_SESSION); session_destroy(); echo '1'; } When the front-end request exits, just log out of the session and return 1 to the front-end JS for processing. Note that get_client_ip() in the above code is a function to obtain the client IP, which cannot be listed due to space limitations. http://www.bkjia.com/PHPjc/631694.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631694.htmlTechArticleThis article mainly talks about the combination of ajax and php in jquery to achieve the user login effect without refreshing. Friends in need You can refer to it. In this example, we use Mysql database to create a use...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!