1. 程式人生 > >PHP生成加減演算法方式的驗證碼

PHP生成加減演算法方式的驗證碼

這是在網上找的一個demo,我加入了一部分程式碼。可以使用。
這裡需要說明一下,我們呼叫這個驗證碼類應該在一個單獨的控制器方法中使用。
生成的圖片的演算法是用程式碼生成的,然後把計算值存入session中。
驗證的時候是獲取使用者的輸入值,然後取出服務端的值進行對比

<?php  
namespace mobile\components;
/** 
  * @author fenghuo 
  * 
  * 改造的加減法驗證類 
  * 使用示例 VerifyCode::get(1,2); 
  * 驗證示例 VerifyCode::check($code); 
 */  
class
VerifyCode {
/** * php驗證碼 */ public static function get($one,$two,$prefix = '', $font_size = 28) { //檔案頭... ob_get_clean(); header("Content-type: image/png;charset=utf-8;"); //建立真彩色白紙 $width = $font_size*5; $height
= $font_size+1; $im = @imagecreatetruecolor($width, $height) or die("建立影象失敗"); //獲取背景顏色 $background_color = imagecolorallocate($im, 255, 255, 255); //填充背景顏色 imagefill($im, 0, 0, $background_color); //獲取邊框顏色 $border_color
= imagecolorallocate($im, 200, 200, 200); //畫矩形,邊框顏色200,200,200 imagerectangle($im,0,0,$width - 1, $height - 1,$border_color); //逐行炫耀背景,全屏用1或0 for($i = 2;$i < $height - 2;$i++) { //獲取隨機淡色 $line_color = imagecolorallocate($im, rand(200,255), rand(200,255), rand(200,255)); //畫線 imageline($im, 2, $i, $width - 1, $i, $line_color); } //設定印上去的文字 $firstNum = $one; $secondNum = $two; $actionStr = $firstNum > $secondNum ? '-' : '+'; //獲取第1個隨機文字 $imstr[0]["s"] = $firstNum; $imstr[0]["x"] = rand(2, 5); $imstr[0]["y"] = rand(1, 4); //獲取第2個隨機文字 $imstr[1]["s"] = $actionStr; $imstr[1]["x"] = $imstr[0]["x"] + $font_size - 1 + rand(0, 1); $imstr[1]["y"] = rand(1,5); //獲取第3個隨機文字 $imstr[2]["s"] = $secondNum; $imstr[2]["x"] = $imstr[1]["x"] + $font_size - 1 + rand(0, 1); $imstr[2]["y"] = rand(1, 5); //獲取第3個隨機文字 $imstr[3]["s"] = '='; $imstr[3]["x"] = $imstr[2]["x"] + $font_size - 1 + rand(0, 1); $imstr[3]["y"] = 3; //獲取第3個隨機文字 $imstr[4]["s"] = '?'; $imstr[4]["x"] = $imstr[3]["x"] + $font_size - 1 + rand(0, 1); $imstr[4]["y"] = 3; //文字 $text = ''; //寫入隨機字串 for($i = 0; $i < 5; $i++) { //獲取隨機較深顏色 $text_color = imagecolorallocate($im, rand(50, 180), rand(50, 180), rand(50, 180)); $text .= $imstr[$i]["s"]; //畫文字 imagechar($im, $font_size, $imstr[$i]["x"], $imstr[$i]["y"], $imstr[$i]["s"], $text_color); } session_start(); $_SESSION[$prefix.'verifycode'] = $firstNum > $secondNum ? ($firstNum - $secondNum) : ($firstNum + $secondNum); //顯示圖片 ImagePng($im); //銷燬圖片 ImageDestroy($im); } public static function check($code) { if(trim($_SESSION[$prefix.'verifycode']) == trim($code)) { return true; } else { return false; } } }