This article mainly introduces the relevant information of PHP AJAX verification code to verify user login in detail. Interested friends can refer to it. I hope it will be helpful to everyone.
One advantage of using AJAX to verify user login is that the jump page does not need to be refreshed. In addition, it is safer to use the verification code, so I wrote it down after a while. A total of three files are used:
yz.php: The PHP file that generates the verification code. The verification code will be in the SESSION for comparison and call during login
index.php: HTML file for user login
loginCheck.php: File for verifying user login
The following is analyzed one by one:
yz.php file
<?php session_start(); //生成验证码图 Header("Content-type: image/PNG"); //长与宽 $im = imagecreate(44,18); // 设置背景色: $back = ImageColorAllocate($im, 245,245,245); // 填充背景色: imagefill($im,0,0,$back); srand((double)microtime()*1000000); $vcodes; //生成4位数字 for($i=0;$i<4;$i++){ $font = ImageColorAllocate($im, rand(100,255),rand(0,100),rand(100,255)); $authnum=rand(1,9); $vcodes.=$authnum; imagestring($im, 5, 2+$i*10, 1, $authnum, $font); } //加入干扰象素 for($i=0;$i<100;$i++){ $randcolor = ImageColorallocate($im,rand(0,255),rand(0,255),rand(0,255)); imagesetpixel($im, rand()%70 , rand()%30 , $randcolor); } ImagePNG($im); ImageDestroy($im); // 将四位的验证码保存在 SESSION 里,登录时调用对比 $_SESSION["VCODE"]=$vcodes; ?>
##index .php: Note, do not take $_SESSION["VCODE"] in this file, otherwise it will be taken one step later, and the previous verification code can be displayed only after refreshing.
Verify in loginCheck.php Okay<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html;charset=gb2312"> <title>管理后台| 请登录</title> <link rel="stylesheet" type="text/css" href="\css\a.css"> <style type="text/css"> <!-- #main{ font-family:宋体; font-size:10pt; text-align:center; margin-top:510px; } body{ background-attachment:fixed; background-position:center; background-image:url(./images/w2.jpg); background-repeat: no-repeat; } #authCode{background-Color:#F8F9FF;} table{text-align:center;} //--> </style> <script type="text/javascript" src="./js/trim.js"></script> <script type="text/javascript"> <!-- function clearX(){ document.getElementById('authCode').value=""; } // 点击图片重新获得新的验证码: function getVCode() { var vcode=document.getElementById('vcode'); vcode.src ='yz.php?nocache='+new Date().getTime(); } //定义XMLHttpRequest对象 var xmlHttp; // 创建 XMLHttpRequest: function createXmlHttpRequest(){ var xmlHttp=null; try{ // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); }catch(e){ // Internet Explorer try{ xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } // AJAX 检查登录: 有密码,要用POST 提交 function login(){ var authCode=trim(document.getElementById('authCode').value); var username=trim(document.getElementById('username').value); var password=trim(document.getElementById('password').value); if(username=="" || password=="" || authCode==""){ alert("请输入用户名和密码和验证码!"); return false; }else{ if(!xmlHttp) xmlHttp=createXmlHttpRequest(); var send_string="username="+username+"&password="+password+"&authCode="+authCode+"&fresh="+Math.random(); xmlHttp.open("POST","loginCheck.php",true); xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlHttp.send(send_string); xmlHttp.onreadystatechange=function(){ if(xmlHttp.readystate==4 && xmlHttp.status==200){ var answer=xmlHttp.responseText; if(answer=="ok") //跳转到管理中心页面 window.location.href="adminCenter.php"; else{ alert("用户名密码或验证码不正确! 请重新输入!"); document.getElementById('username').focus(); } } } } } //--> </script> </head> <body onload="document.getElementById('username').focus();"> <p id="main"> <table> <tr> <td>用户名:<input type="text" id="username" /></td> <td>密 码:<input type="password" id="password" /></td> <td>验证码:<input type="text" id="authCode" size="6" maxlength="4" value="验证码" onfocus="clearX()"/></td> <td><img src="/static/imghwm/default1.png" data-src="yz.php" class="lazy" id="vcode" alt="看不清?点击换一张" onclick="getVCode()" /></td> <td><input id="loginButton" type="submit" value="登 录" onclick="login()"/></td> </tr> </table> </p> </body> </html>
loginCheck.php File to verify user login
<?php session_start(); include("../conn/connDB.php"); // 取得POST过来的参数: $username=$_POST["username"]; $password=md5($_POST["password"]); $authCode=$_POST["authCode"]; $feedback="no"; //对比是否==SESSION中的验证码,不能放在客户端做,否则取不正确的值 if($authCode==$_SESSION["VCODE"]){ $SQL="select * from users where username='$username' and password='$password'"; $result=mysql_query($SQL); $rows=mysql_num_rows($result); if($rows==1) // 验证成功 $feedback="ok"; $_SESSION["admin"]=true; //为了后台安全,存入SESSION,表明 ADMIN 已登录,供后面调用 } echo $feedback; ?>Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study. Related recommendations:
PHP object-oriented programming OOP inheritance usage detailed explanation
PHP object-oriented programming class definition Detailed explanation of usage
PHP MYSQL simple interactive site development detailed explanation
The above is the detailed content of PHP+Ajax implements verification code to verify user login. For more information, please follow other related articles on the PHP Chinese website!

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.


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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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),
