PHP封装一个生成验证码的函数

整体的思路:
1、准备画布
2、生成颜色
3、生成的字符范围
4、开始写字
5、插入干扰线(点)
6、指定输出的类型
7、准备输出图片
8、销毁

<?php
// 生成随机验证码的方法
function verify($width = 100, $height = 40, $num = 5, $type = 3)
{
    // 1、准备画布
    $image = imagecreatetruecolor($width, $height);
    imagefilledrectangle($image, 0, 0, $width, $height, lightColor($image)); //给画布填充一个浅色背景
    // 2、生成颜色

    // 3、需要什么字符
    $string = '';
    switch ($type) {
        case 1: //0-9的数字
            $str = '0123456789';
            //str_shuffle($str); 随机打乱$str 
            $string = substr(str_shuffle($str), 0, $num);
            break;
        case 2: //a-b的字母
            $arr = range('a', 'z');
            shuffle($arr);
            $tmp = array_slice($arr, 0, $num);
            $string = join('', $tmp);
            break;
        case 3: //0-9 a-z A-Z的随机组合
            $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $string = substr(str_shuffle($str), 0, $num);
            break;
    }

    // 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 < 5; $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(10, $height), deepColor($image));
    }

    // 6、指定输出的类型
    header('Content-type:image/png');

    // 7、准备输出图片
    imagepng($image);

    // 8、销毁
    imagedestroy($image);

    return $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));
}

verify();
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。