现在市场上大部分不再使用简单的数字字母验证码,转而使用的是中文验证码或者滑块验证码,本文主要是对中文验证码的记录,方便以后查阅。
<?php
verify_chinese();
function verify_chinese($width=120,$height=40,$num=4,$type=2){
$image = imagecreatetruecolor($width,$height);
imagefilledrectangle($image, 0, 0, $width, $height, lightColor($image));
$string = '';
$temp = array();
switch ($type) {
case 1:
$arr = array('你','我','他','是','这','量','的','个','哦','吧','好','合','上','收','阿','看','噢','包','开','城','车','妹','弟');
shuffle($arr);
$temp = array_slice($arr, 0,4);
$string = join('',$temp);
break;
case 2:
$arr = array('走马观花','欲言又止','马到功成','火烧赤壁','草船借箭','未卜先知','逢凶化吉','知无不言','言无不尽','真真切切','孺子可教','凿壁偷光','悬梁刺股','围魏救赵','纸上谈兵','声东击西','醉翁之意','高山流水','绕梁三日','波涛汹涌','风平浪静','波澜不惊','紫气东来');
shuffle($arr);
$tem = array_slice($arr,0,1);
$string = join('',$tem);
$temp = char2arr($string);
break;
}
//开始写字
for ($i=0; $i <count($temp); $i++) {
imagettftext($image, 18, mt_rand(-10,10), floor($width/$num*$i)+5, mt_rand(25,$height-10), darkColor($image), "yz.ttf", $temp[$i]);
}
//干扰点
for ($i=0; $i < 50; $i++) {
imagesetpixel($image, mt_rand(0,$width), mt_rand(0,$height), darkColor($image));
}
header("Content-type:image/png");
imagepng($image);
imagedestroy($image);
return $string;
}
//浅色
function lightColor($image){
return imagecolorallocate($image, mt_rand(130,255), mt_rand(130,255), mt_rand(130,255));
}
//深色
function darkColor($image){
return imagecolorallocate($image, mt_rand(0,120), mt_rand(0,120), mt_rand(0,120));
}
//将中文字符串转成数组
function char2arr($str)
{
$length = mb_strlen($str, 'utf-8');
$array = [];
for ($i=0; $i<$length; $i++)
$array[] = mb_substr($str, $i, 1, 'utf-8');
return $array;
}
?>
ps:中文数组部分可自行用其他方式存储并导入,为方便演示直接用创建数组来弄。