php验证码生成函数

使用gd2扩展(在php.ini中将;extension=gd2的注释符号;删除)生成验证码,可能失败的原因是某些字体不支持数字和字母。默认的字体文件路径是:C:\\Windows\\Fonts;当不设置保存路径的时候,会将验证码图片以文件形式发送到前端。下面是代码:
function generateIdentifyCode($n_CharNum,$n_Size,$s_SavePath=null,$s_DefaultFontPath = "C:\\Windows\\Fonts")
{
    $a_FontPathArray = [];
    $r_file =opendir($s_DefaultFontPath);
    while(false !== ($s_FontFile = readdir($r_file))){
        if(strchr($s_FontFile,'.ttf') != false || strchr($s_FontFile,'.TTF') != false)
            $a_FontPathArray[] = $s_DefaultFontPath.'\\'.$s_FontFile;
    }
    $a_Code = [];
    $s_Code = '';
    for ($i = 0; $i < $n_CharNum; $i++) {
        $n_Aera = rand(0,2);
        if($n_Aera == 0){
            $char = chr(rand(48,57));
            $a_Code[] = $char;
            $s_Code .= $char;
        }
        elseif($n_Aera ==1){
            $char = chr(rand(65,90));
            $a_Code[] = $char;
            $s_Code .= $char;
        }
        else{
            $char = chr(rand(97,122));
            $a_Code[] = $char;
            $s_Code .= $char;
        }
    }
    $r_Img = imagecreatetruecolor($n_Size*$n_CharNum,$n_Size*1.25);
    imagefill($r_Img,0,0,imagecolorallocate($r_Img,255,255,255));
    $a_Color[] = imagecolorallocate($r_Img,255,0,0);
    $a_Color[] = imagecolorallocate($r_Img,0,255,0);
    $a_Color[] = imagecolorallocate($r_Img,0,0,255);
    for($i = 0;$i < $n_CharNum; $i++){
        $n_Angle = rand(-5,5);
        $r_Color = $a_Color[rand(0,count($a_Color)-1)];
        $s_FontPath = $a_FontPathArray[rand(0,count($a_FontPathArray)-1)];
        if(@imagettftext($r_Img,$n_Size,$n_Angle,$i*$n_Size,$n_Size,$r_Color,$s_FontPath,$a_Code[$i]) == false){
            return false;
        }
    }
    if($s_SavePath == null){
        header('Content-Type:image/jpeg');
        imagejpeg($r_Img,null,100);

    }else{
        imagejpeg($r_Img,$s_SavePath,100);
        return $s_Code;
    }
}

/* 函数调用 */
for($i = 0;$i<100;$i++){
    if(true == ($s_Code = generateIdentifyCode(4,200,"./identifyCode/identifyCode$i.jpeg")))
        echo $s_Code;
    else
        echo "generation failed!";
    echo "<br>";
}
echo "success";
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值