thinkphp是一款基于mvc模式的開源web應用框架,它提供了諸多優秀的功能和特性,讓開發者能夠更加高效地開發web應用。其中之一便是驗證碼功能。驗證碼,全稱為“圖形驗證碼”,是一種用于防止惡意機器人注冊或登錄的技術手段。通常情況下,當用戶輸入錯誤的驗證碼時,網站會刷新或重新生成一張驗證碼圖片。但是有一些用戶遇到了thinkphp驗證碼錯誤卻不刷新的問題,這是怎么回事呢?
一、問題描述
Thinkphp中,驗證碼的生成和校驗使用的是Thinkphp自帶的驗證碼類庫。在使用該類庫時,用戶會發現出現了一種情況,即當驗證碼輸入錯誤時,網站不會立即刷新驗證碼。如果用戶連續多次輸入錯誤的驗證碼,網站并沒有更新驗證碼,這讓用戶感到非常不便。
二、問題分析
該問題的出現原因是因為在Thinkphp的驗證碼類庫中,存在一個屬性$reset為false的方法。當該屬性值為false時,即不刷新驗證碼,直至過期為止。所以當用戶多次輸入錯誤的驗證碼時,網站不會更新驗證碼。
立即學習“PHP免費學習筆記(深入)”;
三、解決方法
針對該問題,解決方法也很簡單,只需要把$reset屬性值修改為true即可。修改方法如下:
在ThinkPHP/Library/Think/Verify.class.php中找到以下代碼:
//是否畫混淆曲線 public $useCurve = true; //是否添加雜點 public $useNoise = true; //驗證碼圖片寬度 public $imageW = 130; //驗證碼圖片高度 public $imageH = 50; //驗證碼位數 public $length = 4; //驗證碼字體大小(px) public $fontSize = 25; //是否畫顏色背景 public $useZh = false; //驗證碼種子 protected $seed = '123456789QWERTYUIOPASDFGHJKLZXCVBNM'; //生成驗證碼 public function entry(){ //驗證碼字符 $this->code = $this->makeCode(); session($this->seKey,$this->code);//驗證碼保存到SESSION中 $width = ($this->length* $this->fontSize*0.9 + $this->fontSize*1.5); $height = $this->fontSize*2; if( $this->useZh ){ $width = 230; $height = 50; } //創建圖像 $this->image = imagecreate($width,$height); //設置背景 if($this->useZh) imagecolorallocate($this->image,244, 220, 215); else{ $this->bkcolor = imagecolorallocate($this->image, 255, 255, 255); imagefill($this->image,0,0,$this->bkcolor); } //混淆曲線 if ($this->useCurve) { $this->writeCurve(); } //雜點 if ($this->useNoise) { $this->writeNoise(); } //驗證碼 $this->writeCode(); header("Cache-Control: max-age=1, s-maxage=1, no-cache, must-revalidate"); header("Content-type: image/png;charset=utf8"); imagepng($this->image); imagedestroy($this->image); }
將其中的$reset屬性值修改為true,修改后的代碼如下:
//是否畫混淆曲線 public $useCurve = true; //是否添加雜點 public $useNoise = true; //驗證碼圖片寬度 public $imageW = 130; //驗證碼圖片高度 public $imageH = 50; //驗證碼位數 public $length = 4; //驗證碼字體大小(px) public $fontSize = 25; //是否畫顏色背景 public $useZh = false; //驗證碼種子 protected $seed = '123456789QWERTYUIOPASDFGHJKLZXCVBNM'; //生成驗證碼 public function entry(){ //驗證碼字符 $this->code = $this->makeCode(); session($this->seKey,$this->code);//驗證碼保存到SESSION中 $width = ($this->length* $this->fontSize*0.9 + $this->fontSize*1.5); $height = $this->fontSize*2; if( $this->useZh ){ $width = 230; $height = 50; } //創建圖像 $this->image = imagecreate($width,$height); //設置背景 if($this->useZh) imagecolorallocate($this->image,244, 220, 215); else{ $this->bkcolor = imagecolorallocate($this->image, 255, 255, 255); imagefill($this->image,0,0,$this->bkcolor); } //混淆曲線 if ($this->useCurve) { $this->writeCurve(); } //雜點 if ($this->useNoise) { $this->writeNoise(); } //驗證碼 $this->writeCode(); // 以下為代碼修改 $this->reset = true; header("Cache-Control: max-age=1, s-maxage=1, no-cache, must-revalidate"); header("Content-type: image/png;charset=utf8"); imagepng($this->image); imagedestroy($this->image); }
修改完后,保存并重新提交即可。
四、結論
本文介紹了Thinkphp驗證碼錯誤不刷新的問題出現原因和解決方法。只需修改一行代碼,即可解決該問題。實際上,在使用任何框架時,出現問題的情況都是不可避免的。不過只要我們積極地去尋找解決方法,問題總會被解決。