<?php
/**
* [code description]
* @param integer $width [验证码宽度]
* @param integer $height [验证码高度]
* @param integer $num [验证码个数]
* @param integer $type [验证码类型 1:纯数字 2:字母 3:数字加字母 4:汉字]
* @return [type] [description]
*/
function code($width=160,$height=40,$num=4,$type=3){
header('Content-Type:image/jpeg');
// 1创建画布
$img = imagecreatetruecolor($width, $height);
// 2 画布分配颜色
$back =imagecolorallocate($img, 255, 255, 255);
$font =imagecolorallocate($img,mt_rand(100,220),mt_rand(100,220),mt_rand(100,220));
$xuehua = imagecolorallocate($img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
// 3填充色
imagefill($img, 0,0, $back);
// 4画布操作
switch ($type) {
case '1':
// 随机获取 num个数字
$b= array_rand(range('0','9'),4);
$a =join($b);
break;
case '2':
// 随机获取4个小写字母
$b =array_rand(array_flip(range('a','z')),4);
$a =join($b);
break;
case '3':
// 随机获取 num 个 数字和字母
$b =array_rand(array_flip(array_merge(range('a','z'),range('0','9'))),4);
$a =join($b);
break;
case '4';
// 随机 num 个汉字
$str='去年月杜特尔特总统成功访华中菲关系实现全面改善当前两国政治互信不断加深务实合作全面开展海上对话合作得以重启中菲关系呈现不断向好发展势头给两国人民带来了实实在在的利益促进了地区和平稳定';
$b = array_rand(array_flip(str_split($str,3)),4);
$a =join($b);
break;
}
if ($type== 4) {
for ($i=0; $i <$num; $i++) {
$x=($width/$num)*$i+10;
imagettftext($img, mt_rand(20,36), mt_rand(0,20), $x, mt_rand(25,30),$font, './STKAITI.TTF',$b[$i]);
}
}else{
// 画每个字母
for ($i=0; $i <$num; $i++) {
$x=($width/$num)*$i+10;
imagettftext($img, mt_rand(20,36), mt_rand(0,20), $x, mt_rand(25,30),$font, './STKAITI.TTF',$a[$i]);
}
}
// 画干扰点
for ($i=0; $i <100 ; $i++) {
imagesetpixel($img, mt_rand(0,150), mt_rand(0,50), $font);
}
// 雪花背景
for ($i=1; $i<100; $i++) {
imageString($img,1,mt_rand(0,$width),mt_rand(0,$height),"*",$xuehua);
}
// 画干扰直线
$n = mt_rand(1,5);
for($i = 0; $i < $n; $i++){
imageline($img, mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width),mt_rand(0,$height),$font);
}
// 把验证码存起来 这是字符串 在未来会使用到
$_SESSION['yzm'] = $a;
// strcasecmp() 比较字符串
// 5 输出或保存
imagejpeg($img);
// 6 销毁画布
imagedestroy($img);
}
code();