使用 PHP 類來生成驗證碼的示例:
class Captcha
{
protected $width = 100; // 驗證碼寬度
protected $height = 30; // 驗證碼高度
protected $length = 4; // 驗證碼長度
protected $font_size = 16; // 驗證碼字體大小
public function generate()
{
session_start(); // 啓動會話
// 創建圖像對象
$image = imagecreatetruecolor($this->width, $this->height);
// 設定背景色
$bg_color = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bg_color);
// 生成驗證碼字符串
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$str = '';
for ($i = 0; $i < $this->length; $i++) {
$str .= $chars[mt_rand(0, strlen($chars) - 1)];
}
// 把驗證碼字符串存入會話變量
$_SESSION['captcha'] = $str;
// 繪製驗證碼字符串
$text_color = imagecolorallocate($image, 0, 0, 0);
for ($i = 0; $i < $this->length; $i++) {
$x = ($this->width / $this->length) * $i + ($this->width / $this->length - $this->font_size) / 2;
$y = $this->height / 2 + $this->font_size / 2 - 2;
imagettftext($image, $this->font_size, mt_rand(-10, 10), $x, $y, $text_color, __DIR__ . '/arial.ttf', $str[$i]);
}
// 輸出圖像
header('Content-type: image/png');
imagepng($image);
// 釋放資源
imagedestroy($image);
}
public function validate($value)
{
session_start(); // 啓動會話
if (isset($_SESSION['captcha']) && strtolower($_SESSION['captcha']) === strtolower($value)) {
unset($_SESSION['captcha']);
return true;
} else {
return false;
}
}
}使用示例:
客戶端代碼:
<!-- 在 HTML 頁面中引用驗證碼圖片 -->
<img src="captcha.php" alt="驗證碼">
<!-- 提交表單時發送驗證碼字符串 -->
<input type="text" name="captcha">服務器端代碼:
<?php
// 創建驗證碼對象
$captcha = new Captcha();
// 生成驗證碼
$captcha->generate();
// 驗證提交的驗證碼
if ($captcha->validate($_POST['captcha'])) {
echo '驗證通過';
} else {
echo '驗證失敗';
}PS:此代碼僅爲示例,封裝可以更加完善,不建議直接用於生產環境。