PHP+Ajax验证码验证用户登录
(编辑:jimmy 日期: 2025/12/28 浏览:3 次 )
用AJAX 验证用户登录的一个好处是不刷新跳转页面,外加用到验证码就更安全了,摸索的写了下。一共用到三个文件:
yz.php: 生成验证码的PHP 文件,将验证码将在SESSION 里,供登录时对比调用
index.php: 用户登录的HTML 文件
loginCheck.php: 验证用户登录的文件
下面一一解析:
yz.php 文件
<"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;
"VCODE"], 否则会取晚一步的,刷新后才能显示上一个验证码
在 loginCheck.php 里验证就好了
<!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="/UploadFiles/2021-04-02/trim.js">
loginCheck.php 验证用户登录的文件
<"../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;
?>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇:PHP+Ajax实现验证码的实时验证
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。