以session方式进行传递
前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="login.php" method="post" >
<input type="text" id="username" name="user" placeholder="User">
<input type="password" id="password" name="pass" placeholder="Pass">
<img src="./vcode.php" alt=""> <!--触发php验证码-->
<input type="text" name="vcode" id="vcode" placeholder="Code">
<input type="submit" value="登录">
</form>
</body>
</html>
后端
<?php
session_start(); //开启session接受vcode发来的验证码
//收集前端数据
$user=$_POST['user'];
$pwd=$_POST['pass'];
$code=$_POST['vcode'];
// echo $user.$pwd.$code;
if(strtolower($code)!==@strtolower($_SESSION['num'])){
die('验证码失败');
}else{
unset($_SESSION['num']); //删除使用过的验证码,@不显示错误日志
}
include 'db.php';
$rows=obj_prepare_rows1($user,$pwd);
if ($rows==1){
$_SESSION['user']=$user;
$_SESSION['isLogin']=true;
echo ('longin-pass');
}else{
echo ('longin-ace');
}
?>
mysql预处理部分
function obj_prepare_rows1($user,$pwd){
$con=new mysqli('IP','用户名','密码','库',端口);
// $sql="insert into users(username,password) values(?,?);";
$sql="select * from users where username=? and password=?;";
$stmt=$con->prepare($sql);
$stmt->bind_param('ss',$user,$pwd);
$stmt->execute();
//存储结果
$stmt->store_result();
// echo $stmt->num_rows();// DQL 查询结果行数
// echo $stmt->affected_rows; //DML 受影响的行数,例如修改密码的行数
// return $stmt->affected_rows;
return $stmt->num_rows();
}
验证码部分
<?php
$num=vcode(); //触发函数获取返回值
session_start(); //开启session
$_SESSION['num']=$num; //发送
function vcode(){
//声明PHP头部
header('content-type:image/png');
//准备画布
$img=imagecreate(80,20);
//准备随机字符
$st="abdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSDUVWXYZ";
$num=substr(str_shuffle($st),0,4); //取随机字符前四位
//设置背景色
imagecolorallocate($img,200,200,100); //图片,R,G,B值
//设置字体颜色
$color=imagecolorallocate($img,100,100,100);
//装载字符在图片上
imagestring($img,5,15,4,$num,$color); //图片,数字位置,数字,字体颜色颜色
//设置干扰元素
for($i=0;$i<20;$i++){
imagesetpixel($img,rand(0,80),rand(0,20),$color);
}
//输出图片
imagepng($img);
//销毁图片
imagedestroy($img);
return $num;
}