隨著互聯網的快速發展,驗證碼已經成為網站和應用程序中廣泛應用的安全認證方式。傳統的驗證碼大多使用英文字符和數字,但有時我們可能需要支持中文字符的驗證碼。本文將詳細介紹如何使用PHP生成支持中文字符的驗證碼圖片,並提供具體的代碼示例。
<?php
$chineseChars = array('一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '百', '千', '萬', '億', '天', '地', '王', '趙', '錢', '孫');
?>
<?php
$code = ''; // 驗證碼初始化為空
for ($i = 0; $i < 3; $i++) {
$index = mt_rand(0, count($chineseChars) - 1); // 隨機選擇字符
$code .= $chineseChars[$index]; // 拼接字符
}
?>
<?php
$width = 120; // 畫布寬度
$height = 40; // 畫布高度
// 創建畫布
$image = imagecreate($width, $height);
// 設置背景顏色
$bgColor = imagecolorallocate($image, 255, 255, 255); // 白色背景
// 隨機選擇驗證碼文字顏色
$textColor = imagecolorallocate($image, mt_rand(0, 150), mt_rand(0, 150), mt_rand(0, 150));
// 中文字體路徑
$fontFile = 'path/to/chinese_font.ttf';
// 繪製驗證碼文字
imagettftext($image, 20, 0, 10, 30, $textColor, $fontFile, $code);
// 輸出驗證碼圖片到瀏覽器
header('Content-Type: image/png');
imagepng($image);
// 銷毀圖像資源
imagedestroy($image);
?>
<?php
session_start();
// 存儲驗證碼到Session
$_SESSION['captcha'] = $code;
?>
接下來,您可以將驗證碼圖片嵌入到HTML表單中,以便用戶輸入驗證碼進行驗證。
<form action="verify.php" method="post">
<input type="text" name="code" placeholder="請輸入驗證碼">
<button type="submit">提交</button>
</form>