php随机验证码生成器

php随机验证码生成器

<?php
//调用验证码生成器
verify();
/**
 * 随机验证码生成器
 * @param int $width - 画布宽度
 * @param int $height - 画布高度
 * @param int $num - 字符个数
 * @param int $charType - 字符类型 1-数字,2-小写字母, 3-数字,大小写字母混合
 */
function verify($width = 100, $height = 40, $num = 5, $charType = 3)
{

    // 1 创建画布
    $image = imagecreatetruecolor($width, $height);

    // 2 创建颜色


    // 3 定义随机数据
    $string = getRandomStr($charType, $num);

    // 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], creColor($image, 1));
    }
    // 4 干扰线
    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), creColor($image, 2));
    }

    //干扰点
    for ($i = 0; $i < 50; $i++) {
        imagesetpixel($image, mt_rand(0, $width), mt_rand(0, $height), creColor($image, 2));
    }
    //指定输出的类型
    header("Content-type:image/png");

    // 5 输出到浏览器或者存放到本地
    imagepng($image);

    // 6 销毁资源
    imagedestroy($image);
}

/**
 * 随机字符串设置
 * @param $type -选择字符类型 1-数字,2-小写字母, 3-数字,大小写字母混合
 * @param $num - 设置字符串长度
 * @return false|string|null $string 字符串
 */
function getRandomStr($type, $num)
{
    $string = null;
    switch ($type) {
        case 1:
            //声明字符串
            $str = '0123456789';
            //截取字符串
            $string = substr(str_shuffle($str), 0, $num);
            break;

        case 2:
            //声明字符串
            $array = range('a', 'z');
            //打乱数组
            shuffle($array);
            //截取
            $tmp = array_slice($array, 0, $num);
            $string = join('', $tmp);
            break;
        case 3:
            //声明字符串
            $str = join(range(0, 9)) . join(range('a', 'z')) . join(range('A', 'Z'));
            $string = substr(str_shuffle($str), 0, $num);
            break;
    }
    return $string;
}

/**
 * 颜色创建
 * @param $image - 画布
 * @param $colorType 1-浅色 2-深色
 * @return false|int imagecolorallocate
 */
function creColor($image, $colorType)
{
    switch ($colorType) {
        case 1:
            //浅色130-255
            return imagecolorallocate($image, mt_rand(130, 255), mt_rand(130, 255), mt_rand(130, 255));
            break;
        case 2:
            //深色0-120
            return imagecolorallocate($image, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));
            break;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值