PHP 產生圖形驗證碼需依賴 GD 庫。執行 phpinfo() 搜尋 gd 區塊,若未啟用請修改 php.ini 取消 extension=gd 註解並重啟服務。
<?php
// 建立 100x30 像素真彩色畫布
$image = imagecreatetruecolor(100, 30);
// 分配白色背景
$bgcolor = imagecolorallocate($image, 255, 255, 255);
// 填充背景
imagefill($image, 0, 0, $bgcolor);
// 輸出 PNG 標頭
header('Content-Type: image/png');
imagepng($image);
// 釋放資源
imagedestroy($image);
?>
使用 imagestring() 將隨機字元寫入圖片:
$fontcolor = imagecolorallocate($image, rand(0,255), rand(0,255), rand(0,255)); $fontsize = 5; // 1-5 內建字體大小 $x = 10; $y = 5; $code = 'A7k9'; // 實際應由隨機產生 imagestring($image, $fontsize, $x, $y, $code, $fontcolor);
for ($i = 0; $i < 200; $i++) {
$color = imagecolorallocate($image, rand(50,255), rand(50,255), rand(50,255));
imagesetpixel($image, rand(0,99), rand(0,29), $color);
}
for ($i = 0; $i < 5; $i++) {
$color = imagecolorallocate($image, rand(50,255), rand(50,255), rand(50,255));
imageline($image, rand(0,99), rand(0,29), rand(0,99), rand(0,29), $color);
}
<?php
session_start();
$image = imagecreatetruecolor(100, 40);
$bgcolor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgcolor);
$checkcode = '';
$rawstr = 'abcdefghjkmnopqrstuvwxyz23456789ABCDEFGHJKLMNOPQRSTUVWXYZ'; // 排除易混淆字元
$x = 5;
for ($i = 0; $i < 4; $i++) {
$fontsize = rand(6, 8);
$fontcolor = imagecolorallocate($image, rand(0,100), rand(0,100), rand(0,100));
$char = $rawstr[rand(0, strlen($rawstr)-1)];
$checkcode .= $char;
$x += 20;
$y = rand(10, 20);
imagestring($image, $fontsize, $x, $y, $char, $fontcolor);
}
// 干擾點與線
for ($i = 0; $i < 200; $i++) {
$color = imagecolorallocate($image, rand(50,255), rand(50,255), rand(50,255));
imagesetpixel($image, rand(0,99), rand(0,39), $color);
}
for ($i = 0; $i < 4; $i++) {
$color = imagecolorallocate($image, rand(150,255), rand(150,255), rand(150,255));
imageline($image, rand(0,99), rand(0,39), rand(0,99), rand(0,39), $color);
}
$_SESSION['checkcode'] = strtolower($checkcode); // 統一小寫比對
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
<img id="captcha" src="captcha.php?r=<?php echo rand(); ?>" />
<a href="javascript:void(0);" onclick="refreshCaptcha()">看不清,換一張</a>
<input type="text" name="checkcode" placeholder="請輸入驗證碼" />
<script>
function refreshCaptcha() {
document.getElementById('captcha').src = 'captcha.php?r=' + Math.random();
}
</script>
<?php
session_start();
if (isset($_POST['checkcode'])) {
if (strtolower($_POST['checkcode']) === $_SESSION['checkcode']) {
echo "<font color='green'>驗證通過</font>";
} else {
echo "<font color='red'>驗證碼錯誤</font>";
}
exit;
}
?>
phpinfo() 中已啟用。imagecreatetruecolor() 建立真彩色畫布,imagefill() 填充背景。imagestring() 繪製文字,搭配隨機字體大小、顏色、位置增加辨識難度。imagesetpixel()、干擾線 imageline() 有效對抗 OCR 識別。$_SESSION,比對時統一轉小寫(strtolower())避免大小寫困擾。Math.random() 更新 src 參數實現「換一張」無快取效果。掌握上述技巧,即可快速部署安全且使用者友善的驗證碼系統。建議後續可嘗試更高階的 TTF 字體(imagettftext())、扭曲變形、中文驗證碼等進階玩法。