驗證碼是防止機器人惡意提交表單的基礎防線。本文提供兩個完整實作:英數混合版與中文字符版,涵蓋 Session 驗證、干擾線/像素、字體渲染等核心技術。
特點:輕量、相容性高、無需外部字體檔案
<?php
header("Content-type: image/png");
session_start();
$chars = 'abcdefghijkmnpqrstuvwxyz23456789'; // 排除易混淆字符
$code = '';
for ($i = 0; $i < 4; $i++) {
$code .= $chars[mt_rand(0, strlen($chars) - 1)];
}
$_SESSION['captcha_code'] = $code;
// 建立畫布
$im = imagecreate(80, 30);
$bg = imagecolorallocate($im, 230, 230, 230);
$text_color = imagecolorallocate($im, 0, 0, 0);
$noise_color = imagecolorallocate($im, 180, 180, 180);
// 干擾像素
for ($i = 0; $i < 100; $i++) {
imagesetpixel($im, mt_rand(0, 80), mt_rand(0, 30), $noise_color);
}
// 干擾線
for ($i = 0; $i < 3; $i++) {
imageline($im, mt_rand(0, 80), mt_rand(0, 30), mt_rand(0, 80), mt_rand(0, 30), $noise_color);
}
// 繪製文字
imagestring($im, 5, 10, 5, $code, $text_color);
imagepng($im);
imagedestroy($im);
?>
特點:辨識難度高、需 TTF 字體檔、支援中文字符
<?php
header("Content-type: image/png");
session_start();
$chinese_chars = ["人","出","來","友","學","孝","仁","義","禮","廉","忠","國","中","易","白","者","火","土","金","木","雷","風","龍","虎","天","地","生","暈","菜","鳥","田","三","百","錢","福","愛","情","獸","蟲","魚","九","網","新","度","哎","唉","啊","哦","儀","老","少","日","月","星"];
$code = '';
for ($i = 0; $i < 4; $i++) {
$code .= $chinese_chars[array_rand($chinese_chars)];
}
$_SESSION['captcha_code'] = $code;
// TrueColor 畫布
$im = imagecreatetruecolor(130, 40);
$bg = imagecolorallocate($im, 20, 20, 20);
$text_color = imagecolorallocate($im, 255, 255, 255);
// 需準備 gbk.ttf 或其他中文字體檔
$font = __DIR__ . '/fonts/gbk.ttf';
imagettftext($im, 20, 0, 15, 28, $text_color, $font, $code);
imagepng($im);
imagedestroy($im);
?>
<!-- HTML 表單 -->
<img src="captcha.php" id="captchaImg" onclick="this.src='captcha.php?'+Math.random()" style="cursor:pointer" />
<input type="text" name="captcha_input" required />
<!-- PHP 驗證 -->
<?php
session_start();
if (strtolower($_POST['captcha_input']) !== strtolower($_SESSION['captcha_code'])) {
die('驗證碼錯誤');
}
// 通過驗證,處理業務邏輯
?>
mt_rand() 或 random_int() 替代 rand()