最輕量的驗證碼實作:PHP GD 繪製 4 碼英數字符,前端 <img> + JS 點擊換圖(附加時間戳查詢字串防瀏覽器快取)。無需 Session、資料庫,適合快速原型或教學示範。
index.html<html>
<head><title>驗證碼</title></head>
<script>
function refreshCaptcha() {
var img = document.getElementsByTagName("img")[0];
img.src = "gd.php?t=" + (new Date().getTime().toString(36));
}
</script>
</head>
<body>
<img src="gd.php" /> <a href="#" onclick="refreshCaptcha()">換一張</a>
</body>
</html>
gd.php<?php
$im = imagecreate(50, 20);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$code = '';
for ($i = 0; $i < 4; $i++) {
$code .= $chars[rand(0, 61)];
}
imagestring($im, 3, rand(10, 20), rand(0, 10), $code, $white);
header("Content-type: image/jpeg");
imagejpeg($im);
imagedestroy($im);
?>
$code 存入 Session/Redis 驗證Securimage、Gregwar/Captcha 等成熟庫