PHP开发学习笔记之生成验证码

来源:互联网 发布:linux pdf编辑器 编辑:程序博客网 时间:2024/05/22 01:42

使用GD库做验证码

1. 创建画布和笔刷

$image = imagecreatetruecolor($width, $height);$white = imagecolorallocate($image, 255, 255, 255);$black = imagecolorallocate($image, 0, 0, 0);

2. 用矩形填充画布

imagefilledrectangle($image, 1, 1, $width - 2, $height - 2, $white);

3. 根据指定的类型和长度获取随机字符串并保存到$chars

function getRandomString($type = 2, $length = 4){    //根据type判断验证码的类型,如数字,数字+字符,字符+字符    if($type == 1){        //join函数将数组里的元素用分隔符连接成字符串返回,rang函数返回数组        $chars = join("", range(0,9));    }elseif ($type == 2){        //array_merge函数将多个数组合并成一个数组        $chars = join("", array_merge(range("a", "z"), range("A", "Z")));    }elseif ($type == 3){        $chars = join("", array_merge(range("a", "z"), range("A", "Z"), range(0, 9)));    }else{        exit("验证码类型错误!");    }    //如果请求长度大于chars,则报错    if($length > strlen($chars)){        exit("验证码字符串长度不够");    }    //str_shuffle函数随机打乱一个字符串    $str = str_shuffle($chars);    return substr($str, 0, $length);}$chars = getRandomString($type, $length);

4. 将验证码保存到session中

$_SESSION[$session_name] = $chars;

5. 将指定字符填充到画布中,使用imagettftext来给文字增添样式并填充

for ($i = 0; $i < $length; $i++) {    $size = mt_rand(14, 18);    $angle = mt_rand(-15, 15);    $x = 5 + $i * $size;    $y = mt_rand(20, 26);    $color = imagecolorallocate($image, mt_rand(50, 90), mt_rand(100, 140), mt_rand(150, 200));    $fontfile = "../fonts/" . $fontfiles[mt_rand(0, count($fontfiles) - 1)];    $text = substr($chars, $i, 1);    imagettftext($image, $size, $angle, $x, $y, $color, $fontfile, $text);}

6. 添加妨碍元素

//画布随机填充黑点,默认填充if ($pixel) {    for ($i = 0; $i < $pixel; $i++) {        imagesetpixel($image, mt_rand(0, $width - 1), mt_rand(0, $height - 1), $black);    }}//画布随机填充直线if ($line) {    for ($i = 0; $i < $line; $i++) {        imageline($image, mt_rand(0, $width - 1), mt_rand(0, $height - 1), mt_rand(0, $width - 1), mt_rand(0, $height - 1), $black);    }}

7. 显示验证码图片

ob_clean(); //清除输出header("content-type:image/gif");imagegif($image);imagedestroy($image);

ps:

其中特别要注意的是,在显示图片前一定要调用ob_clean()清除输入,否则会经常出现“本地图片错误”的提示。

1 0
原创粉丝点击