PHP jQuery Ajax implements user login and exit
PHP jQuery Ajax implements user login and exit
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 database
In this example we use Mysql database to create a user table with the following table structure:
?
2 3
|
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; |
1 2 | 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 he clicks "Exit", he will 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.
?
2 3
4 5 6
|
User loginif(isset($_SESSION['user'])){ ?>, Congratulations on your successful login! This is the login to this site. The last time you logged in to this site was:
|
1 2 |
1 2 3 | $(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:
?
2 3
|
$("input:text,textarea,input:password").focus(function() { $(this).addClass("cur_select"); }); $("input:text,textarea,input:password").blur(function() { $(this).removeClass("cur_select"); }); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 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("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 you have logged into this site. The last time you logged in to this site was: " json.login_time " |
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 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 div = "
id='pass' /> |
login.php
Based on 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 updated and assembled json data is passed to the front desk.
?
|
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; } $md5pass = md5($pass); //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'] = 'Wrong username or password! '; } echo json_encode($arr); //Output json data } elseif ($action == 'logout') { //Exit unset($_SESSION); session_destroy(); echo '1'; } |
When the frontend requests to exit, just log out of the session and return 1 to the frontend 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.
The above is the entire content of this article, I hope you all like it.

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

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.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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