PHP生成验证码
<?php
//1.宽高 字母 数字 字母数字混合线 干扰线 干扰点 背景色 字体的颜色
verfify();
function verfify( $width =100 ,$height = 40, $num = 5, $type = 1)
{
//1.准备画布
$image = imagecreatetruecolor($width, $height);
//2.生成颜色
//3.需要的字符
$string ='';
switch($type)
{
case 1:
$str = '0123456789';
$string = substr(str_shuffle($str), 0 , $num);
break;
case 2:
$arr = range('a','z');
shuffle($arr);
$tmp = array_slice($arr,0,$num);
$string = join('',$tmp);
break;
case 3:
$str = '0123456789abcdefjhijklmnopqrstuvwxyzABCDEFJHIJKLMNOPQRSTUVWXYZ';
$string = substr(str_shuffle($str),0, $num);
break;
}
//给背景填充浅色
imagefilledrectangle($image,0,0,$width,$height,lightColor($image));
//4.写入画布
for($i = 0; $i<$num;$i++)
{
$x = floor($width/$num)*$i;
$y = mt_rand(10,$height - 20);
imagechar($image, 5 ,$x,$y,$string[$i],deepColor($image));
}
//5.画干扰线
for($i = 0;$i<$num;$i++)
{
imagearc($image,mt_rand(10,$width),mt_rand(10,$height),mt_rand(10,$width),
mt_rand(10,$height),mt_rand(0,10),mt_rand(0,270),deepColor($image));
}
//干扰点
for($i = 0;$i<50;$i++)
{
imagesetpixel($image,mt_rand(0,$width),mt_rand(0,$height),deepColor($image));
}
//6.指定输出类型
header('Content-type:image/png');
//7.准备输出图片
imagepng($image);
//8.销毁
imagedestroy($image);
echo $string;
}
//浅颜色
function lightColor($image)
{
return imagecolorallocate($image , mt_rand(130, 255),mt_rand(130, 255),mt_rand(130, 255));
}
//深颜色
function deepColor($image){
return imagecolorallocate($image , mt_rand(0, 120),mt_rand(0, 120),mt_rand(0, 120));
}