生成混合驗(yàn)證碼,并封裝成函數(shù),文件名:buildVerifyCode.func.php
//range( a , z )將括號中的內(nèi)容作為鍵值生成一個(gè)索引數(shù)組 //array_merge($array1,$array2)合并兩個(gè)數(shù)組中的鍵值,生成新索引數(shù)組 //array_flip()將括號中的內(nèi)容,鍵名與鍵值對換 //array_rand($array,$length)隨機(jī)取出$array中$length長度的鍵名作為新數(shù)組的鍵值,生成一個(gè)索引數(shù)組 //join( ,$array)以空連接數(shù)組中的值,以數(shù)組的內(nèi)容生成字符串
?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;}
測試生成的驗(yàn)證碼是否正確,文件名: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);
生成圖像驗(yàn)證碼,具體注釋有空再寫,文件名:getVerifyCodeImg.func.php
?php$width=100;$height=30;//創(chuàng)建畫布,默認(rèn)底色黑色,rgb0,0,0$image=imagecreatetruecolor($width,$height);//創(chuàng)建白色,方便覆蓋畫布$white=imagecolorallocate($image,255,255,255);//創(chuàng)建白色矩形覆蓋原始畫布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);
相關(guān)推薦:
tp5框架ajax異步添加數(shù)據(jù)的代碼實(shí)現(xiàn)
thinkphp中無限級欄目的排序?qū)崿F(xiàn)代碼
以上就是php實(shí)現(xiàn)生成混合驗(yàn)證碼與圖像驗(yàn)證碼并測試(代碼)的詳細(xì)內(nèi)容,PHP教程
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請第一時(shí)間聯(lián)系我們修改或刪除,多謝。
新聞熱點(diǎn)
疑難解答
圖片精選