php
<?php
session_start(); // 启动会话以存储验证码值
// 生成随机验证码字符
function generateCaptcha($length = 6) {
$characters = ’0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’;
$captcha = ’’;
for ($i = 0; $i < $length; $i++) {
$captcha .= $characters[rand(0, strlen($characters) - 1)];
}

return $captcha;
// 存储验证码值到会话变量中
$_SESSION[’captcha’] = generateCaptcha();
// 创建验证码图像
function createCaptchaImage($captcha) {
$imageWidth = 200; // 图像宽度
$imageHeight = 80; // 图像高度
$fontFile = ’path/to/font.ttf’; // 字体文件路径(可选)
$fontSize = 30; // 字体大小(可选)
$color = imagecolorallocate(imagecreatetruecolor($imageWidth, $imageHeight), rand(0, 255), rand(0, 255), rand(0, 255)); // 随机背景颜色
$backgroundColor = imagecolorallocate($image, 255, 255, 255); // 背景颜色为白色
$textColor = imagecolorallocate($image, 0, 0, 0); // 文字颜色为黑色
imagefilledrectangle($image, 0, 0, $imageWidth - 1, $imageHeight - 1, $color); // 填充背景色
imagettftext($image, $fontSize, 0, 10, $imageHeight - 10, $textColor, $fontFile, $captcha); // 在图像上添加验证码文字(使用 TrueType 字体)
return $image; // 返回图像资源句柄
// 生成验证码图像并显示在页面上
$captchaImage = createCaptchaImage($_SESSION[’captcha’]); // 创建验证码图像资源句柄
header(’Content-type: image/png’); // 设置响应头为 PNG 图像格式
imagepng($captchaImage); // 输出图像为 PNG 格式到浏览器或保存到文件系统中(根据需要修改)
imagedestroy($captchaImage); // 销毁图像资源句柄以释放内存资源
?>
上述代码中,generateCaptcha()函数用于生成随机验证码字符,并将其存储在会话变量中。createCaptchaImage()函数用于创建包含验证码的图像,你可以根据需要修改图像的大小、颜色和字体等参数,通过调用createCaptchaImage()函数生成验证码图像,并将其以 PNG 格式输出到浏览器或保存到文件系统中,请确保将path/to/font.ttf替换为你实际使用的字体文件路径。





