PHP验证码功能实现
什么是验证码
就是将一串随机产生的数字或符号,生成一幅图片,图片里加上一些干扰象素(防止OCR)。
由用户肉眼识别其中的验证码信息,输入表单提交网站验证,验证成功后才能使用某项功能。
作用的是现代的验证码一般是防止机器批量注册的,防止机器批量发帖回复。
目前,不少网站为了防止用户利用机器人自动注册、登录、灌水,刷票都采用了验证码技术。
第一步:先新建imgcode.php文件,用写验证码的代码
<?php
function get_str($length=1){
$chars='3456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$s=str_shuffle($chars);
$str=substr($s,0,$length);
return $str;
}
$width=80;
$height=34;
$img=imagecreatetruecolor($width,$height);
$bgcolor=imagecolorallocate($img,238,238,238);
$textcolor=imagecolorallocate($img,255,0,0);
imagefilledrectangle($img,0,0,$width,$height,$bgcolor);
$get_code1=get_str();
$get_code2=get_str();
$get_code3=get_str();
$get_code4=get_str();
$font='images/texb.ttf';
imagettftext($img,16,mt_rand(-30,30),1,26,$textcolor,$font,$get_code1);
imagettftext($img,16,mt_rand(-30,30),20,26,$textcolor,$font,$get_code2);
imagettftext($img,16,mt_rand(-30,30),40,26,$textcolor,$font,$get_code3);
imagettftext($img,16,mt_rand(-30,30),60,26,$textcolor,$font,$get_code4);
for($i=0;$i<=10;$i++){
imagesetpixel($img,mt_rand(0,$width),mt_rand(0,$height),imagecolorallocate($img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255)));
}
for($i=0;$i<=5;$i++){
imageline($img,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width),mt_rand(0,$height),imagecolorallocate($img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255)));
}
session_start();
$get_code=$get_code1.$get_code2.$get_code3.$get_code4;
$_SESSION['imgcode']=$get_code;
header('Content-Type:image/png');
imagepng($img);
?>