昨天学的忘发了 今天补上

一个验证码的生成

先写一个验证码生成的函数

function getCode($length=4,$type=0)
{
    $str="0123456789qwertyuipasdfghjkzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
    $t=strlen($str)-1;
    switch ($type) {
        case 0:
            $t=9;
            break;
        case 1:
            $t=33;
            break;
        
        default:
        $t=strlen($str)-1;
        break;

    }
    $code = "";
    for ($i=0; $i <$length ; $i++) { 
        $code .=$str[rand(0,$t)];
    }
    return $code;
}

有0-9,a-z,A-z组成,33个是少了几个混淆的字母

 strlen 的运用

 还有rand 随机产生一个整数

写完 一个随机的验证码  

可以echo  $code;

看一下这个随机的四个字符

当然这不是完  还需要做一个画布 就是一个图像 需要让产生出来的随机验证码出现在画布上

还可以增加干扰线 以及干扰点

$lg=4;
$code = getCode($lg,3);
$width = $lg*20;
$height = 30;
$im = imagecreatetruecolor($width,$height);
$color[] = imagecolorallocate($im,111,0,255);
$color[] = imagecolorallocate($im,0,0,55);
$color[] = imagecolorallocate($im,241,0,241);
$color[] = imagecolorallocate($im,11,0,125);
$bg = imagecolorallocate($im,240,240,240);
for ($i=0; $i <200 ; $i++) { 
    $cc = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
    imagesetpixel($im,rand(0,$width),rand(0,$height),$cc);
}

for ($i=0; $i <5 ; $i++) { 
    $cc = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
    imageline($im,rand(0,$width),rand(0,$height),rand(0,$width),rand(0,$height),$cc);
}

imagefill($im,0,0,$bg);
for ($i=0; $i <$lg ; $i++) { 
    imagettftext($im,18,rand(-40,40), 8+(18*$i),24, $color[rand(0,3)], "./ht.ttf",$code[$i]);
}

header("Content-type:text/html; charset=utf-8");
header("Content-Type:image/png");
imagepng($im);


imagedestroy($im);

使用  GD和图像处理函数

imagecreatetruecolor创建一个画布

imagefill

将验证码放入画布

imagettftext  参数有点多
 
imagecolorallocate 在画布中创建一个颜色

imagesetpixel    接下来创建干扰点

在for里面创建一个点  循环两百次

imageline然后是干扰线


header  发送原生http头

大概的意思就是 在PHP文件中创建html的内容比如  定义编码  创建图像域

imagepng  输出验证码图片

imagedestroy 销毁图像  不保存


好了 这就结束了

猜你喜欢

转载自www.cnblogs.com/id652084176/p/8945879.html
今日推荐