随着互联网的快速发展,验证码已经成为网站和应用程序中广泛应用的安全认证方式。传统的验证码大多使用英文字符和数字,但有时我们可能需要支持中文字符的验证码。本文将详细介绍如何使用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>