search
HomeBackend DevelopmentPHP TutorialPHP implements refresh-free login and exit based on Ajax
PHP implements refresh-free login and exit based on AjaxJun 11, 2018 pm 01:57 PM
ajaxjqueryphpLog inquit

This article uses Ajax to log in and log out without refreshing, thus improving the user experience. If the user is logged in, the user's relevant login information is displayed, otherwise the login form is displayed.

User login and logout functions are used in many places, and in some projects, we need to use Ajax to log in. After successful login, only part of the page is refreshed, thus improving the user experience. This article will use PHP and jQuery to implement the 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(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;

Then insert into the user table A piece of user information data:

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

index.php

After the user enters the user name and password, the user is prompted to log in successfully and displays the relevant login information. If the user clicks "Exit ”, then exit to the user login interface.
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.

<p id="login"> 
   <h3 id="用户登录">用户登录</h3> 
   <?php 
   if(isset($_SESSION[&#39;user&#39;])){ 
   ?> 
   <p id="result"> 
    <p><strong><?php echo $_SESSION[&#39;user&#39;];?></strong>,恭喜您登录成功!</p> 
    <p>您这是第<span><?php echo $_SESSION[&#39;login_counts&#39;];?></span>次登录本站。</p> 
    <p>上次登陆本站的时间是:<span><?php echo date(&#39;Y-m-d H:i:s&#39;,$_SESSION[&#39;login_time&#39;]);?> 
</span></p><p><a href=&#39;#&#39; id=&#39;logout&#39;>【退出】</a></p> 
   </p> 
   <?php }else{?> 
   <p id="login_form"> 
     <p><label>用户名:</label> <input type="text" class="input" name="user" id="user" /></p> 
     <p><label>密 码:</label> <input type="password" class="input" name="pass" id="pass" /> 
</p> 
     <p class="sub"> 
       <input type="submit" class="btn" value="登 录" /> 
     </p> 
   </p> 
   <?php }?> 
</p>

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 The example has been written in a slightly simple style, please view 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 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 code used is as follows:

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

The next thing to do is to present different styles when the input box gains and loses focus. For example, in this example, different border colors are used. 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 the login button, 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.

$(".btn").live(&#39;click&#39;,function(){ 
  var user = $("#user").val(); 
  var pass = $("#pass").val(); 
  if(user==""){ 
    $(&#39;<p id="msg" />&#39;).html("用户名不能为空!").appendTo(&#39;.sub&#39;).fadeOut(2000); 
    $("#user").focus(); 
    return false; 
  } 
  if(pass==""){ 
    $(&#39;<p id="msg" />&#39;).html("密码不能为空!").appendTo(&#39;.sub&#39;).fadeOut(2000); 
    $("#pass").focus(); 
    return false; 
  } 
  $.ajax({ 
    type: "POST", 
    url: "login.php?action=login", 
    dataType: "json", 
    data: {"user":user,"pass":pass}, 
    beforeSend: function(){ 
      $(&#39;<p id="msg" />&#39;).addClass("loading").html("正在登录...").css("color","#999") 
.appendTo(&#39;.sub&#39;); 
    }, 
    success: function(json){ 
      if(json.success==1){ 
        $("#login_form").remove(); 
        var p = "<p id=&#39;result&#39;><p><strong>"+json.user+"</strong>,恭喜您登录成功!</p> 
        <p>您这是第<span>"+json.login_counts+"</span>次登录本站。</p> 
        <p>上次登录本站的时间是:<span>"+json.login_time+"</span></p><p> 
        <a href=&#39;#&#39; id=&#39;logout&#39;>【退出】</a></p></p>"; 
        $("#login").append(p); 
      }else{ 
        $("#msg").remove(); 
        $(&#39;<p id="errmsg" />&#39;).html(json.msg).css("color","#999").appendTo(&#39;.sub&#39;) 
.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 to #login Under the element, complete the login operation.
User exit: 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.

$("#logout").live(&#39;click&#39;,function(){ 
  $.post("login.php?action=logout",function(msg){ 
    if(msg==1){ 
       $("#result").remove(); 
       var p = "<p id=&#39;login_form&#39;><p><label>用户名:</label> 
       <input type=&#39;text&#39; class=&#39;input&#39; name=&#39;user&#39; id=&#39;user&#39; /></p> 
       <p><label>密 码:</label> <input type=&#39;password&#39; class=&#39;input&#39; name=&#39;pass&#39; 
id=&#39;pass&#39; /></p> 
       <p class=&#39;sub&#39;><input type=&#39;submit&#39; class=&#39;btn&#39; value=&#39;登 录&#39; /></p> 
       </p>"; 
       $("#login").append(p); 
    } 
  }); 
});

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 Yes, if the comparison is successful, the user's login information will be updated and the json data will be assembled and sent to the front desk.

session_start(); 
require_once (&#39;connect.php&#39;); 
 
$action = $_GET[&#39;action&#39;]; 
if ($action == &#39;login&#39;) { //登录 
  $user = stripslashes(trim($_POST[&#39;user&#39;])); 
  $pass = stripslashes(trim($_POST[&#39;pass&#39;])); 
  if (emptyempty ($user)) { 
    echo &#39;用户名不能为空&#39;; 
    exit; 
  } 
  if (emptyempty ($pass)) { 
    echo &#39;密码不能为空&#39;; 
    exit; 
  } 
  $md5pass = md5($pass); //密码使用md5加密 
  $query = mysql_query("select * from user where username=&#39;$user&#39;"); 
 
  $us = is_array($row = mysql_fetch_array($query)); 
 
  $ps = $us ? $md5pass == $row[&#39;password&#39;] : FALSE; 
  if ($ps) { 
    $counts = $row[&#39;login_counts&#39;] + 1; 
    $_SESSION[&#39;user&#39;] = $row[&#39;username&#39;]; 
    $_SESSION[&#39;login_time&#39;] = $row[&#39;login_time&#39;]; 
    $_SESSION[&#39;login_counts&#39;] = $counts; 
    $ip = get_client_ip(); //获取登录IP 
    $logintime = mktime(); 
    $rs = mysql_query("update user set login_time=&#39;$logintime&#39;,login_ip=&#39;$ip&#39;, 
login_counts=&#39;$counts&#39;"); 
    if ($rs) { 
      $arr[&#39;success&#39;] = 1; 
      $arr[&#39;msg&#39;] = &#39;登录成功!&#39;; 
      $arr[&#39;user&#39;] = $_SESSION[&#39;user&#39;]; 
      $arr[&#39;login_time&#39;] = date(&#39;Y-m-d H:i:s&#39;,$_SESSION[&#39;login_time&#39;]); 
      $arr[&#39;login_counts&#39;] = $_SESSION[&#39;login_counts&#39;]; 
    } else { 
      $arr[&#39;success&#39;] = 0; 
      $arr[&#39;msg&#39;] = &#39;登录失败&#39;; 
    } 
  } else { 
    $arr[&#39;success&#39;] = 0; 
    $arr[&#39;msg&#39;] = &#39;用户名或密码错误!&#39;; 
  } 
  echo json_encode($arr); //输出json数据 
} 
elseif ($action == &#39;logout&#39;) { //退出 
  unset($_SESSION); 
  session_destroy(); 
  echo &#39;1&#39;; 
}

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. Due to space limitations, it cannot be listed. You can download the source code to view it.

Okay, a complete set of user login and logout procedures is completed. There are inevitable shortcomings. Everyone is welcome to criticize and correct.

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

The role and usage of type hints in PHP

PHP implements image watermark according to Dynamic addition function of color environment

PHP method to implement multi-threading

The above is the detailed content of PHP implements refresh-free login and exit based on Ajax. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php怎么设置implode没有分隔符php怎么设置implode没有分隔符Apr 18, 2022 pm 05:39 PM

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment