PHP implements refresh-free login and exit based on Ajax
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>用户登录</h3> <?php if(isset($_SESSION['user'])){ ?> <p id="result"> <p><strong><?php echo $_SESSION['user'];?></strong>,恭喜您登录成功!</p> <p>您这是第<span><?php echo $_SESSION['login_counts'];?></span>次登录本站。</p> <p>上次登陆本站的时间是:<span><?php echo date('Y-m-d H:i:s',$_SESSION['login_time']);?> </span></p><p><a href='#' id='logout'>【退出】</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('click',function(){ var user = $("#user").val(); var pass = $("#pass").val(); if(user==""){ $('<p id="msg" />').html("用户名不能为空!").appendTo('.sub').fadeOut(2000); $("#user").focus(); return false; } if(pass==""){ $('<p id="msg" />').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(){ $('<p id="msg" />').addClass("loading").html("正在登录...").css("color","#999") .appendTo('.sub'); }, success: function(json){ if(json.success==1){ $("#login_form").remove(); var p = "<p id='result'><p><strong>"+json.user+"</strong>,恭喜您登录成功!</p> <p>您这是第<span>"+json.login_counts+"</span>次登录本站。</p> <p>上次登录本站的时间是:<span>"+json.login_time+"</span></p><p> <a href='#' id='logout'>【退出】</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 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('click',function(){ $.post("login.php?action=logout",function(msg){ if(msg==1){ $("#result").remove(); var p = "<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>"; $("#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 ('connect.php'); $action = $_GET['action']; if ($action == 'login') { //登录 $user = stripslashes(trim($_POST['user'])); $pass = stripslashes(trim($_POST['pass'])); if (emptyempty ($user)) { echo '用户名不能为空'; exit; } if (emptyempty ($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'; }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
