php如何创建验证码

本文介绍了一种生成随机字符串验证码的方法,并使用PHP结合GD库实现验证码图片。文章详细解释了如何生成不同类型的随机字符串,如何将这些字符串绘制到图片上,并提供了完整的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先创建一个生成随机字符串

/**
 * 生成验证码
 * @param int $type
 * @param int $length
 * @return string
 */
function buildRandomString($type=1,$length=4){
    if ($type == 1) {
        $chars = join ( "", range ( 0, 9 ) );
    } elseif ($type == 2) {
        $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 ) ) );
    }
    if ($length > strlen ( $chars )) {
        exit ( "字符串长度不够" );
    }
    $chars = str_shuffle ( $chars );
    return substr ( $chars, 0, $length );
}




通过GD库做验证图片

require_once 'string.func.php';

//通过GD库做验证码

function verifyImage($type=1,$length=4,$pixel=0,$line=0,$sess_name = "verify"){ 
    //创建画布
    $width = 80;
    $height = 28;
    $image = imagecreatetruecolor ( $width, $height );
    $white = imagecolorallocate ( $image, 255, 255, 255 );
    $black = imagecolorallocate ( $image, 0, 0, 0 );
    //用填充矩形填充画布
    imagefilledrectangle ( $image, 1, 1, $width - 2, $height - 2, $white );
    $chars = buildRandomString ( $type, $length );
    $_SESSION [$sess_name] = $chars;
    //这里需要创建一个文件夹来存放字体
    $fontfiles = array ("LHANDW.TTF","LSANS.TTF","LTYPE.TTF");

    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 );
        $fontfile = "../fonts/" . $fontfiles [mt_rand ( 0, count ( $fontfiles ) - 1 )];
        $color = imagecolorallocate ( $image, mt_rand ( 50, 90 ), mt_rand ( 80, 200 ), mt_rand ( 90, 180 ) );
        $text = substr ( $chars, $i, 1 );
        imagettftext ( $image, $size, $angle, $x, $y, $color, $fontfile, $text );
    }
    //创建模糊点
    if ($pixel) {
        for($i = 0; $i < 50; $i ++) {
            imagesetpixel ( $image, mt_rand ( 0, $width - 1 ), mt_rand ( 0, $height - 1 ), $black );
        }
    }
    //创建模糊线
    if ($line) {
        for($i = 1; $i < $line; $i ++) {
            $color = imagecolorallocate ( $image, mt_rand ( 50, 90 ), mt_rand ( 80, 200 ), mt_rand ( 90, 180 ) );
            imageline ( $image, mt_rand ( 0, $width - 1 ), mt_rand ( 0, $height - 1 ), mt_rand ( 0, $width - 1 ), mt_rand ( 0, $height - 1 ), $color );
        }
    }
    //展示图片
    header ( "content-type:image/gif" );
    imagegif ( $image );
    imagedestroy ( $image );
}

调用该函数
verifyImage();
这里写图片描述
verifyImage(2,4,4,4);
这里写图片描述
verifyImage(3,4,4,4);

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kitt15

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值