CAPTCHA(全自動區分計算機和人類的圖靈測試)廣泛用於防止暴力破解、刷票、垃圾留言。本文將帶您從零開始,使用 PHP GD 庫構建一個支援干擾線、噪點、隨機字符的動態驗證碼,並封裝為可複用函數。
header('Content-Type: image/png');$im = imagecreatetruecolor(200, 200);$blue = imagecolorallocate($im, 0, 102, 255); imagefill($im, 0, 0, $blue);imagepng($im);imagedestroy($im);_code()/**
* 驗證碼生成函數
* @param int $_width 畫布寬度(建議:6 位約 125px,8 位約 175px)
* @param int $_height 畫布高度(建議 30-50px)
* @param int $_rnd_code 驗證碼位數
* @param bool $_flag 是否顯示邊框
*/
function _code($_width = 125, $_height = 35, $_rnd_code = 6, $_flag = false) {
session_start();
// 1. 生成隨機字符(十六進制)
$_nmsg = '';
for ($i = 0; $i < $_rnd_code; $i++) {
$_nmsg .= dechex(mt_rand(0, 15));
}
$_SESSION['code'] = $_nmsg; // 存入 Session 驗證
// 2. 創建畫布
$_img = imagecreatetruecolor($_width, $_height);
$_white = imagecolorallocate($_img, 255, 255, 255);
imagefill($_img, 0, 0, $_white);
// 3. 邊框
if ($_flag) {
$_black = imagecolorallocate($_img, 0, 0, 0);
imagerectangle($_img, 0, 0, $_width - 1, $_height - 1, $_black);
}
// 4. 干擾線
for ($i = 0; $i < 6; $i++) {
$_rnd_color = imagecolorallocate($_img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imageline($_img, mt_rand(0, $_width), mt_rand(0, $_height), mt_rand(0, $_width), mt_rand(0, $_height), $_rnd_color);
}
// 5. 噪點(雪花)
for ($i = 0; $i < 100; $i++) {
$_rnd_color = imagecolorallocate($_img, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
imagestring($_img, 1, mt_rand(1, $_width), mt_rand(1, $_height), '*', $_rnd_color);
}
// 6. 繪製驗證碼字符
for ($i = 0; $i < strlen($_SESSION['code']); $i++) {
$_rnd_color = imagecolorallocate($_img, mt_rand(0, 100), mt_rand(0, 150), mt_rand(0, 200));
// 隨機位置增加識別難度
$x = $i * $_width / $_rnd_code + mt_rand(1, 10);
$y = mt_rand(1, $_height / 2);
imagestring($_img, 5, $x, $y, $_SESSION['code'][$i], $_rnd_color);
}
// 7. 輸出與清理
header('Content-Type: image/png');
imagepng($_img);
imagedestroy($_img);
}
<img src="captcha.php" alt="驗證碼" onclick="this.src='captcha.php?'+Math.random()" />
點擊圖片即可刷新,captcha.php 中只需 require 'global.func.php'; _code(); 即可。
imagettftext() 替換內建字體,增加變形與旋轉