项目中经常会遇到一些登陆验证,支付验证等等一系列安全验证的策略。实现方法多种多样,下面就来讲解下如何用php生成简单的文字+数字组合的验证码: 原理解释: a>实质上是在服务器端随机生成验证码,将其存储在$_SESSION中。 b>然后将验证码写在图片上,将图片发送至客户端,用户输入图片的上的验证码,递交给服务器。 c>服务端再与$_SESSION中存储的信息比对,一致则通过,否则不通过。
第一步:在服务器端如何生成验证码:<yzm.php>
<?php
session_start();
$str='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
//创建画布
$width = 100;
$height = 35;
$img = imagecreatetruecolor($width, $height);
$color = imagecolorallocate($img,0xcc,0xcc,0xcc);
//填充颜色
imagefill($img,0,0,$color);
//画噪点
for ($i=0;$i<300;$i++){
$color = imagecolorallocate($img,rand(0,100),rand(0,100),rand(0,100));
$x=rand(0,$width);
$y=rand(0,$height);
imagesetpixel($img,$x,$y,$color);
}
//画噪线
for ($i=0;$i<8;$i++){
$color = imagecolorallocate($img,rand(0,100),rand(0,100),rand(0,100));
$x1=rand(0,$width);
$y1=rand(0,$height);
$x2=rand(0,$width);
$y2=rand(0,$height);
imageline($img,$x1,$y1,$x2,$y2,$color);
}
//画圆
for ($i=0;$i<6;$i++){
$color = imagecolorallocate($img,rand(0,255),rand(0,255),rand(0,255));
imageellipse($img,rand(0,$width),rand(0,$height),30,30,$color);
}
//画文字
$len = strlen($str);
$font = 'arial.ttf';
$yzm = "";
for ($i=0;$i<4;$i++){
$color = imagecolorallocate($img,rand(0,100),rand(0,100),rand(0,100));
$index = rand(0,$len-1);
$chr = substr($str,$index,1);
$yzm .= $chr;
$x = 10+$i*20;
$y = 20;
//imagettftext(图像资源,字体大小,角度,x坐标,y坐标,$颜色,$字体路径,字符串);
imagettftext($img,20,rand(-50,50),$x,$y,$color,$font,$chr);
}
$_SESSION["yzm"] = $yzm;
//输出画布
header('content-type:image/png');
imagepng($img);
//销毁画布
imagedestroy($img);
?>
第二步:将生成的验证码图片返回给客户端<form.php>
<?php
header("Content-type:text/html;charset=utf-8");//避免出现乱码的情况
if(isset($_REQUEST['authcode'])){
session_start();//使用$_SESSION之前必须使用session_start()
if(strtolower($_REQUEST['authcode'])==$_SESSION["authcode"]){//$_SESSION['authcode']是服务器端存储的验证码,$_REQUEST['authcode']获取客户端输入的信息
echo "<font color='#000cc'>输入正确</font>";
}
else{
echo "<font color='#0000cc'>输入错误</font>";
}
exit();
}
?>