验证码功能:屏蔽机器请求,保障业务不受机器提交请求干扰
//依赖GD扩展
$image=imagecreatetruecolor(100,30);
$bgcolor=imagecolorallocate($image,255,255,255);
imagefill($image,0,0,$bgcolor);//填充
for($i=0;$i<4;$i++){
$fontsize = 6;
$fontcolor = imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120));
$fontcontent = rand(0,9);//产生0~9之间的数字
$x = ($i*100/4+rand(5,10));
$y = rand(5,10);
imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor);
}
//点干扰
for($i=0;$i<200;$i++){
$pointcolor=imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200));
imagesetpixel($image,rand(1,99),rand(1,29),$pointcolor);
}
//线干扰
for($i=0;$i<3;$i++){
$linecolor=imagecolorallocate($image,rand(80,220),rand(80,220),rand(80,220));
imageline($image,rand(1,99),rand(1,29),rand(1,99),rand(1,29),$linecolor);
}
header('content-type:image/png');
imagepng($image);
imagedestroy($image);
?>
captcha.php
这里将验证码保存在session中
// 依赖GD扩展
session_start();
$image=imagecreatetruecolor(100,30);
$bgcolor=imagecolorallocate($image,255,255,255);
imagefill($image,0,0,$bgcolor);//填充
$fontcolor=imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120));
$captch_code = '';
for($i=0;$i<4;$i++){
$fontsize=6;
$fontcolor=imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120));
$data = 'abcdefghijklmnopqrstuvwxyz0123456789';
$fontcontent = substr($data,rand(0,strlen($data)),1);
$captch_code .= $fontcontent;
$x = ($i*100/4) + rand(5,10);
$y = rand(5,10);
imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor);
}
$_SESSION['authcode'] = $captch_code;
//点干扰
for($i=0;$i<200;$i++){
$pointcolor=imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200));
imagesetpixel($image,rand(1,99),rand(1,29),$pointcolor);
}
//线干扰
for($i=0;$i<3;$i++){
$linecolor=imagecolorallocate($image,rand(80,220),rand(80,220),rand(80,220));
imageline($image,rand(1,99),rand(1,29),rand(1,99),rand(1,29),$linecolor);
}
header('content-type:image/png');
imagepng($image);
imagedestroy($image);
?>
form.php
if(isset($_POST['authcode'])){
session_start();
//将验证码中的字母全部转化为小写再与session中的对比
if(strtolower($_POST['authcode']) == $_SESSION['authcode']){
echo "输入正确";
}else{
echo "输入错误";
}
exit();
}
?>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>确认验证码title>
head>
<body>
<form method="post" action="./form.php">
<p>验证码图片:<img src="./captcha1.php?r=" border="1"
width="100" height="30" id="captcha_img">
<a href = "javascript:void(0)" onclick = "document.getElementById('captcha_img').src = './captcha1.php?r='+Math.random()">换一个?
请输入图片中的内容: