思路:大多數網站中的算術驗證碼都是整數形式的,所以我們的運算公式是這樣的
加數 + 加數,被減數 - 減數,被乘數 * 乘數 無非這3種公式。類似A 【+、-、*】 B
所以第一步:我們要封裝一個php函數是生成 類似A 【+、-、*】 B 的驗證碼,第二步:因為我們需要獲取用戶輸入的結果進行驗證碼判斷是否輸入正確,所以在我們生成驗證碼的同時要記錄下運算結果到伺服器中(此處存入session),第三步用戶提交驗證碼與我們存入session中的運算結果進行匹配驗證。
核心PHP代碼:
<?php/*** @param int $width 寬度,默認為100 * @param int $height 高度,默認為50 * @param int $fontSize 字體的大小 默認20 * @return 圖片資源 */function getCaptche($width=120,$height=50,$fontSize=20){ // 開啟session session_start(); // 創建畫布 $img = imagecreatetruecolor($width,$height); // 分配顏色 $color = imagecolorallocate($img,255,255,255); // 填充顏色 imagefill($img,0,0,$color); // 幹擾點 for ($i = 0;$i < 500;$i++){ $pixColor = imagecolorallocate($img,mt_rand(100,200),mt_rand(100,200),mt_rand(100,200)); imagesetpixel($img,mt_rand(0,$width),mt_rand(0,$height),$pixColor); } // 幹擾線 for ($i = 0;$i < 4;$i++){ $lineColor = imagecolorallocate($img,mt_rand(0,120),mt_rand(0,120),mt_rand(0,120)); imageline($img,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width),mt_rand(0,$height),$lineColor); } // 定義一個數組存放運算符號 $arr = ['+','-','*']; // 計算數組的長度 $len = count($arr); // 定義一個1到20的數組 $num = range(1,20); $numLen = count($num); // 定義一個空數組來存放隨機取得的驗證碼 $code = []; for ($i = 0;$i < $len;$i++) { if ($i == 1) { $code[] = $arr[mt_rand(0,$len-1)]; }else { $code[] = $num[mt_rand(0,$numLen-1)]; } } $str = implode($code);// 將數組轉為字符串 $textColor = imagecolorallocate($img,mt_rand(100,200),mt_rand(100,200),mt_rand(100,200)); $fontAngle = 0; $x = ($width - $fontSize*3)/2; $y = ($height - $fontSize) / 2 + $fontSize; // 字體路徑 $font = '/img/inkfree.ttf'; imagettftext($img,$fontSize,$fontAngle,$x,$y,$textColor,$font,$str); $res = getRes($code); // 將函數存放在session中 $_SESSION['res'] = $res; // 輸出圖片 header("content-type:image/png"); imagepng($img);}/** * @param $arr 一個包含運算符號的數組 * @return 返回一個運算結果 */function getRes($arr) { $res = 0; // 判斷數組元素下標為1的運算符號是什麼 switch ($arr[1]){ case '+': $res = $arr[0] + $arr[2]; break; case '-': $sum = $arr[0] - $arr[2]; break; case '*': $res = $arr[0] * $arr[2]; break; } return $res;}$width = 120;$height = 50;$fontSize = 20;//調用函數getCaptche($width,$height,$fontSize);
核心模板代碼:
<!doctype html><html><head><meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>帶運算的驗證碼</title> <style> img { position: relative; top: 20px; } </style></head><body><form action="index.php"> 驗證碼 <input type="text" name="captche"> <img src="./captche.php" alt="點擊刷新"> <br> <button>提交</button></form></body></html><script> // 實現點擊圖片刷新驗證碼 var img = document.querySelector("img"); img.onclick = function () { this.src = this.src+"?m="+Math.random(); }</script>
效果圖如下: