使用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";