這篇文章介紹的内容是關于PHP生成指定位數驗證碼與可控幹擾元素 ,有着一定的參考價值,現在分享給大家,有需要的朋友可以參考一下
生成混合驗證碼,并封裝成函數,檔案名:buildVerifyCode.func.php
//range('a','z')将括号中的内容作為鍵值生成一個索引數組
//array_merge($array1,$array2)合并兩個數組中的鍵值,生成新索引數組
//array_flip()将括号中的内容,鍵名與鍵值對換
//array_rand($array,$length)随機取出$array中$length長度的鍵名作為新數組的鍵值,生成一個索引數組
//join('',$array)以空連接配接數組中的值,以數組的内容生成字元串
function buildVerifyCode($type=2,$length=4){
switch ($type) {
case 0:
$string=join('',array_rand(range(0,9),$length));
break;
case 1:
$string=join('',array_rand(array_flip(array_merge(range('a','z'),range('A','Z'))),$length));
break;
case 2:
$string=join('',array_rand(array_flip(array_merge(range('a','z'),range('A','Z'),range(0,9))),$length));
break;
}
return $string;
}
測試生成的驗證碼是否正确,檔案名:getCode.php
require 'buildVerifyCode.func.php';
echo buildVerifyCode();
// $fontfiles=['msyh.ttc','msyhbd.ttc','msyhl.ttc','simsun.ttc','Sitka.ttc'];
// $fontfile=$fontfiles[mt_rand(0,count($fontfiles)-1)];
// var_dump($fontfile);
生成圖像驗證碼,具體注釋有空再寫,檔案名:getVerifyCodeImg.func.php
$width=100;
$height=30;
//建立畫布,預設底色黑色,rgb0,0,0
$image=imagecreatetruecolor($width,$height);
//建立白色,友善覆寫畫布
$white=imagecolorallocate($image,255,255,255);
//建立白色矩形覆寫原始畫布
imagefilledrectangle($image,1,1,$width-2,$height-2,$white);
require 'buildVerifyCode.func.php';
$type=2;
$length=4;
$verifyCode=buildVerifyCode($type,$length);
for($i=0;$i
$color=imagecolorallocate($image,mt_rand(50,90),mt_rand(80,200),mt_rand(90,150));
$size=mt_rand(14,16);
$angle=mt_rand(-15,15);
$x=($i*100/5)+$size;
$y=mt_rand(20,25);
$fontfiles=['msyh.ttc','msyhbd.ttc','msyhl.ttc','simsun.ttc','Sitka.ttc'];
$fontfile="../fonts/".$fontfiles[mt_rand(0,count($fontfiles)-1)];
$text=substr($verifyCode,$i,1);
imagettftext($image,$size,$angle,$x,$y,$color,$fontfile,$text);
}
$pixel=120;
if($pixel){
$pixelcolor=imagecolorallocate($image,mt_rand(150,170),mt_rand(100,140),mt_rand(90,160));
for($i=0;$i
imagesetpixel($image,mt_rand(0,$width-1),mt_rand(0,$height-1),$pixelcolor);
}
}
$line=4;
if($line){
for($i=0;$i
imageline($image,mt_rand(0,$width-1),mt_rand(0,$height-1),mt_rand(0,$width-1),mt_rand(0,$height-1),$pixelcolor);
}
}
header('content-type:image/png');
imagepng($image);
imagedestroy($image);
相關推薦: