整合「隨機字串產生」與「GD 繪製驗證碼圖片」於單一類別,支援 7 種字元模式(數字、小寫、大寫、大小寫混合、字母數字混合等),提供 getCode() 取得字串、createImage() 直接輸出 PNG,並說明 Session 整合要點。
<?php
class Captcha
{
/** 字元池常數 */
private const POOLS = [
0 => 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', // 預設:大小寫+數字
1 => '0123456789',
2 => 'abcdefghijklmnopqrstuvwxyz',
3 => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
4 => 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
5 => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
6 => 'abcdefghijklmnopqrstuvwxyz0123456789',
];
/**
* 取得隨機字串
* @param int $length 長度(預設 4)
* @param int $mode 模式 0-6(見 POOLS)
* @return string
*/
public static function getCode(int $length = 4, int $mode = 0): string
{
$pool = self::POOLS[$mode] ?? self::POOLS[0];
$max = strlen($pool) - 1;
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= $pool[random_int(0, $max)]; // PHP 7+ 加密安全隨機
}
return $code;
}
/**
* 直接輸出驗證碼 PNG 圖片
* @param string $code 驗證碼字串(若為空自動產生)
* @param int $width 圖片寬
* @param int $height 圖片高
* @param int $fontSize 字體大小 1-5
*/
public static function createImage(string $code = '', int $width = 100, int $height = 36, int $fontSize = 5): void
{
if ($code === '') $code = self::getCode();
$im = imagecreatetruecolor($width, $height);
// 背景:淺灰
$bg = imagecolorallocate($im, 230, 230, 230);
imagefill($im, 0, 0, $bg);
// 干擾線
for ($i = 0; $i < 8; $i++) {
$color = imagecolorallocate($im, random_int(150, 255), random_int(150, 255), random_int(150, 255));
imageline($im, random_int(0, $width), random_int(0, $height), random_int(0, $width), random_int(0, $height), $color);
}
// 干擾點
for ($i = 0; $i < 80; $i++) {
$color = imagecolorallocate($im, random_int(0, 255), random_int(0, 255), random_int(0, 255));
imagesetpixel($im, random_int(0, $width), random_int(0, $height), $color);
}
// 文字繪製(內建字體 1-5)
$textColor = imagecolorallocate($im, random_int(0, 100), random_int(0, 100), random_int(0, 100));
$x = 10; $y = (int)($height * 0.65);
for ($i = 0, $len = strlen($code); $i < $len; $i++) {
$char = $code[$i];
$angle = random_int(-15, 15);
// imagettftext 需 TTF 字體,這裡用內建字體示範
imagestring($im, $fontSize, $x, $y, $char, $textColor);
$x += imagefontwidth($fontSize) + 2;
}
header('Content-Type: image/png');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');
imagepng($im);
imagedestroy($im);
}
}
<?php
session_start();
$_SESSION['captcha'] = Captcha::getCode(6, 1); // 6 位數字
echo json_encode(['code' => $_SESSION['captcha']]); // 實際專案勿直接回傳,需發送簡訊/Email
<!-- HTML -->
<img id="captchaImg" src="captcha.php" alt="點擊換圖" style="cursor:pointer" />
<input name="captcha" placeholder="輸入驗證碼" />
<script>
document.getElementById('captchaImg').onclick = function() {
this.src = 'captcha.php?' + Date.now(); // 防快取
};</script>
<?php
// captcha.php
session_start();
$code = Captcha::getCode(4, 0); // 4 位大小寫+數字
$_SESSION['captcha'] = strtolower($code); // 驗證時不區分大小寫
Captcha::createImage($code);
<?php
session_start();
if (strtolower($_POST['captcha'] ?? '') !== ($_SESSION['captcha'] ?? '')) {
exit('驗證碼錯誤');
}
// 通過,處理業務邏輯...
unset($_SESSION['captcha']); // 用完即銷毀,防重放
imagestring 替換為 imagettftext 載入 .ttf,字體更豐富、抗辨識度更高。session.cookie_httponly=1、session.cookie_secure=1(HTTPS)、session.use_strict_mode=1。