CAPTCHA(全自動區分計算機與人類的圖靈測試),防暴力破解、刷票、灌水。PHP 以 GD 擴展動態生成圖片:
header('Content-Type: image/png')imagecreatetruecolor($w, $h)imagefill()imagepng()imagedestroy()<img src="captcha.php" /><?php
/**
* _code() 驗證碼函數
* @param int $_width 寬度(6位建議 125,4位建議 75)
* @param int $_height 高度
* @param int $_rnd_code 字元數
* @param bool $_flag 是否顯示邊框
*/
function _code($_width = 75, $_height = 25, $_rnd_code = 4, $_flag = false) {
// 1. 產生隨機碼(16進位)
$_nmsg = '';
for ($i = 0; $i < $_rnd_code; $i++) {
$_nmsg .= dechex(mt_rand(0, 15));
}
// 2. 存入 Session
$_SESSION['code'] = $_nmsg;
// 3. 建立畫布
$_img = imagecreatetruecolor($_width, $_height);
$_white = imagecolorallocate($_img, 255, 255, 255);
imagefill($_img, 0, 0, $_white);
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));
imagestring($_img, 5, $i * $_width / $_rnd_code + mt_rand(1, 10), mt_rand(1, $_height / 2), $_SESSION['code'][$i], $_rnd_color);
}
// 7. 輸出與銷毀
header('Content-Type: image/png');
imagepng($_img);
imagedestroy($_img);
}
?>
<?php
session_start();
require dirname(__FILE__).'/includes/global.func.php';
_code(125, 25, 6, false); // 6位碼
?>
<?php
header('Content-Type: text/html; charset=utf-8');
session_start();
require dirname(__FILE__).'/includes/global.func.php';
if ($_GET['action'] == 'verification') {
if (!($_POST['code'] == $_SESSION['code'])) {
_alert_back('驗證碼不正確!');
} else {
_alert_back('驗證碼通過!');
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>驗證碼測試</title>
<script src="js/codeimg.js"></script>
</head>
<body>
<form method="post" action="?action=verification">
驗證碼:<input type="text" name="code" class="code" />
<img src="codeimg.php" id="codeimg" />
<input type="submit" value="驗證" />
</form>
</body>
</html>
// codeimg.js
window.onload = function () {
var code = document.getElementById('codeimg');
code.onclick = function () {
this.src = 'codeimg.php?tm=' + Math.random(); // 加隨機參數防快取
};
};
function _alert_back($msg) {
echo "<script>alert('$msg'); history.back();</script>";
exit;
}
圖片含干擾線、雪花噪點、隨機顏色/位置文字,點擊圖片即時換碼無需重整頁面。