PHP使用GD库封装验证码类
生活随笔
收集整理的這篇文章主要介紹了
PHP使用GD库封装验证码类
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
調(diào)試小技巧:當(dāng)圖片無法顯示時,將header函數(shù)注釋掉就可以看到報錯信息了
字體文件放在當(dāng)前文件目錄的font文件夾中,windows的字體可以到C:\Windows\Fonts目錄下復(fù)制過來,處理好文件名即可
關(guān)于GD庫和面向?qū)ο蟮闹R點可以看我前面幾篇隨筆,直接上代碼了
?
<?php//驗證碼類 namespace vendor;class CaptchaMaker{/*** @desc 制作驗證碼* @param int $width = 450,驗證碼圖片默認(rèn)寬度* @param int $height = 65,驗證碼圖片默認(rèn)高度* @param int $length = 4,驗證碼默認(rèn)字符數(shù)* @param string $fonts = '',驗證碼字體,默認(rèn)為空(內(nèi)部使用默認(rèn)字體)* @param int $level = 2,干擾素級別(1-3),級別越高越難辨認(rèn)* @return null*/public static function getCaptcha($width = 450,$height = 65,$length = 4,$fonts = '',$level = 2){//判定字體資源if(empty($fonts)) $fonts = 'verdana.ttf';$fonts = __DIR__ . '/fonts/' . $fonts; //字體路徑//制作畫布$img = imagecreatetruecolor($width,$height);//分配背景色:隨機(jī)淺色系$bg_color = imagecolorallocate($img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));imagefill($img,0,0,$bg_color);//獲取隨機(jī)字符$captcha = self::getString($length);//保存到session@session_start();$_SESSION['captcha'] = $captcha;//寫入圖片for($i = 0;$i < $length;$i++){//增加顏色$c_color = imagecolorallocate($img, mt_rand(0,60), mt_rand(0,60), mt_rand(0,60));imagettftext($img, mt_rand(15,25), mt_rand(-45,45), $width/($length+1)*($i+1), mt_rand(25,$height-25), $c_color, $fonts, $captcha[$i]);}$interferon_level = $level ? ($level >= 1 && $level <= 3 ? $level: 2) : 2;//增加干擾點$interferon_arr = array('*','(',')','~','^','=','-','+','#','&');for($i = 0;$i < $interferon_level * 100;$i++){$dots_color = imagecolorallocate($img,mt_rand(140,190),mt_rand(140,190),mt_rand(140,190));imagestring($img,mt_rand(1,5),mt_rand(0,$width),mt_rand(0,$height),$interferon_arr[mt_rand(0,9)],$dots_color);}//增加干擾線for($i = 0;$i < $interferon_level * 10;$i++){$line_color = imagecolorallocate($img, mt_rand(80,130), mt_rand(80,130), mt_rand(80,130));//制作線段imageline($img,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width),mt_rand(0,$height),$line_color);imagearc($img,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,360),mt_rand(0,360),$line_color);}//輸出資源header('Content-type:image/png');imagepng($img);imagedestroy($img);}//獲取隨機(jī)字符串private static function getString($length = 4){//定義變量保存數(shù)據(jù)$captcha = '';//循環(huán)隨機(jī)獲取數(shù)據(jù)for($i = 0;$i < $length;$i++){//隨機(jī)確定數(shù)字、大寫字母還是小寫字母switch(mt_rand(1,3)){case 1: //數(shù)字:49-57分別代表1-9$captcha .= chr(mt_rand(49,57)); break;case 2: //小寫字母$captcha .= chr(mt_rand(65,90));break;case 3: //大寫字母$captcha .= chr(mt_rand(97,122));break;}}//返回給調(diào)用處return $captcha;}//驗證驗證碼public static function checkCaptcha($captcha){//與session中存的進(jìn)行對比@session_start();return (strtolower($captcha) === strtolower($_SESSION['captcha']));} } //測試 CaptchaMaker::getCaptcha();?
轉(zhuǎn)載于:https://www.cnblogs.com/chuanzi/p/10410708.html
與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的PHP使用GD库封装验证码类的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: setTimeout使用问题
- 下一篇: Codeforces - 1118D2