最近由于项目需要,图形验证码,就写了一个,为大家详细介绍下实现过程!
1、验证码封装实现方法
//生成验证码
public function get_img_code(){
ob_clean();
cookie('code',NULL);
session('code',NULL);
$code=$this->randStr(4);
cookie('code',$code);
session('code',$code);
$x_size=75;
$y_size=30;
$aimg = imagecreate($x_size,$y_size);
$back = imagecolorallocate($aimg,255, 255, 255);
$border = imagecolorallocate($aimg,204,53,53);
imagefilledrectangle($aimg, 10, 10, $x_size+1, $y_size+1, $back);
imagerectangle($aimg,100,100, $x_size, $y_size, $border);
imageString($aimg,30,20,8, $code,$border);
header("Pragma:no-cache");
header("Cache-control:no-cache");
header("Content-type: image/png");
imagepng($aimg);
imagedestroy($aimg);
}
//生成随机字符串
function rand_str($len){
$chars = array(
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B","D", "E", "F", "G","H","J","L", "M", "N","Q", "R","T", "U","Y", "2","3", "4", "5", "6", "7", "8", "9"
);
$charsLen = count($chars)-1;
shuffle($chars);
$outStr='';
for ($i=0;$i<$len;$i++){
$outStr.=$chars[mt_rand(0,$charsLen)];
}
return $out_str;
}
2.前端展示功能
完成图形验证码
看不清,换一张
您输入的验证码错误,请重新输入