相關(guān)關(guān)鍵詞
關(guān)于我們
最新文章
- PHP中opcode緩存簡單用法分析
- thinkPHP控制器變量在模板中的顯示方法示例
- PHP move_uploaded_file() 函數(shù)(將上傳的文件移動(dòng)到新位置)
- dirname(__FILE__)的含義和應(yīng)用說明
- thinkPHP5框架實(shí)現(xiàn)分頁查詢功能的方法示例
- PHP中單雙號(hào)與變量
- PHP獲得當(dāng)日零點(diǎn)時(shí)間戳的方法分析
- Laravel ORM對Model::find方法進(jìn)行緩存示例詳解
- PHP讀寫文件高并發(fā)處理操作實(shí)例詳解
- 【CLI】利用Curl下載文件實(shí)時(shí)進(jìn)度條顯示的實(shí)現(xiàn)
PHP 用session與gd庫實(shí)現(xiàn)簡單驗(yàn)證碼生成與驗(yàn)證的類方法
驗(yàn)證碼是為了防止機(jī)器灌水給網(wǎng)站帶來污染以及增加服務(wù)器負(fù)擔(dān)而出現(xiàn)的。目前大大小小的網(wǎng)站都有驗(yàn)證碼。今天自己實(shí)現(xiàn)了一個(gè)簡單的驗(yàn)證碼類。說簡單是因?yàn)闆]有加一些干擾的弧線等等,只是將文字旋轉(zhuǎn)了一下。當(dāng)然,因?yàn)樽煮w的原因,要想一眼看出來并不容易。同時(shí),為了避免字母的大小寫與數(shù)字混淆,又去掉了那些看起來很像的字母數(shù)字。
類:
<?php /** *簡單生成驗(yàn)證碼類 */ class Captcha { private $width;//驗(yàn)證碼寬度 private $height;//驗(yàn)證碼高度 private $countOfChars;//字符數(shù) //private $distrubLines;//干擾線條數(shù) private $chars;//隨機(jī)生成的字符串 public function __construct($width=100,$height=30,$countOfChars=4,$distrubLines=2) { //初始化參數(shù) $this->width=$width; $this->height=$height; $this->countOfChars=$countOfChars; session_start(); } /** * 執(zhí)行全部動(dòng)作,生成驗(yàn)證碼并直接輸出 */ public function execute(){ $imageHandle=$this->createImage(); $this->createChars(); $this->drawChars($imageHandle); $this->outImage($imageHandle); } /** * 創(chuàng)建畫布,并隨機(jī)填充顏色 * @return 返回畫布句柄 */ public function createImage(){ $imageHandle= imagecreate($this->width, $this->height); //隨機(jī)背景顏色 $randColor=imagecolorallocate($imageHandle, 50, mt_rand(0, 50), mt_rand(0, 50)); imagefill($imageHandle, 0, 0, $randColor); return $imageHandle; } /** * 生成隨機(jī)字符 */ private function createChars(){ //候選字符 $str='ABCDEFGHJKLMNPQRSTUVWXZabcdefghijkmnpqtuvwx2346789'; $chars=''; for($i=0;$i<$this->countOfChars;$i++){ $chars.=$str[mt_rand(0,strlen($str)-1)]; } $this->chars=$chars; //保存在會(huì)話中 $_SESSION['captcha']=strtolower($chars); } /** * 將字符寫入圖像 * @param type $imageHandle 圖像句柄 */ private function drawChars($imageHandle){ if($this->chars!=null){ $font='/home/WWW/YuWeiLiShuFT.ttf'; for($i=0;$i<strlen($this->chars);$i++){ $color= imagecolorallocate($imageHandle,mt_rand(50, 200),mt_rand(100, 255),255); imagefttext($imageHandle,30, 30,$i*20+10,25,$color,$font,$this->chars[$i]); } } } /** * 輸出圖像 * @param type $imageHandle 圖像句柄 */ private function outImage($imageHandle){ imagepng($imageHandle); imagedestroy($imageHandle); } /** * 判斷用戶輸入的驗(yàn)證碼是否正確 * @param type $usrInput 用戶的輸入 * @return boolean 驗(yàn)證碼是否匹配 */ public static function isRight($usrInput){ if(isset($_SESSION['captcha'])){ if(strtolower($usrInput)==$_SESSION['captcha']){ $_SESSION['captcha']=null; return true; }else{ $_SESSION['captcha']=null; return false; } } } }