生成混合驗證碼,并封裝成函數,文件名:buildVerifyCode.func.php
//range( a , z )將括號中的內容作為鍵值生成一個索引數組 //array_merge($array1,$array2)合并兩個數組中的鍵值,生成新索引數組 //array_flip()將括號中的內容,鍵名與鍵值對換 //array_rand($array,$length)隨機取出$array中$length長度的鍵名作為新數組的鍵值,生成一個索引數組 //join( ,$array)以空連接數組中的值,以數組的內容生成字符串
?phpfunction 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
?phprequire 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
?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 $length;$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 $pixel;$i++){ imagesetpixel($image,mt_rand(0,$width-1),mt_rand(0,$height-1),$pixelcolor);$line=4;if($line){ for($i=0;$i $line;$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);
相關推薦:
tp5框架ajax異步添加數據的代碼實現
thinkphp中無限級欄目的排序實現代碼
以上就是php實現生成混合驗證碼與圖像驗證碼并測試(代碼)的詳細內容,PHP教程
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答