绘制一个宽度为80像素、高度为20像素,由4个字母或数字组成的验证码。
<?php
session_start();
$code = '';
for ($i = 0; $i < 4; $i++) {
$code .= chr(rand(48, 90)); // ASCII码中数字、大写字母和小写字母的范围是48-57、65-90和97-122
}
$_SESSION['code'] = $code;
$image = imagecreate(80, 20);
$background_color = imagecolorallocate($image, 255, 255, 255); // 白色背景
$text_color = imagecolorallocate($image, 0, 0, 0); // 黑色文本
imagestring($image, 5, 10, 3, $code, $text_color); // 在图像中绘制文本
header('Content-Type: image/png'); // 以PNG格式输出图像
imagepng($image); // 输出图像
imagedestroy($image); // 释放内存
?>
要显示验证码,请将上述代码保存为captcha.php文件并在页面中使用以下HTML代码:
<img src="captcha.php" alt="验证码">
这将在页面中显示一个随机生成的验证码。