php
<?php
session_start(); // 启动会话
// 生成随机验证码
$random_code = ’’;
$length = 5; // 验证码长度
for ($i = 0; $i < $length; $i++) {
$random_code .= rand(0, 9); // 生成数字验证码,如果需要字母或其他字符,可以修改此处的范围
$_SESSION[’captcha’] = $random_code; // 将验证码保存到会话中,以便后续验证用户输入

// 创建图像
$width = 100; // 图像宽度
$height = 40; // 图像高度
$image = imagecreatetruecolor($width, $height); // 创建空白图像
// 设置背景颜色并填充背景
$bgColor = imagecolorallocate($image, 255, 255, 255); // 白色背景
imagefill($image, 0, 0, $bgColor);
// 生成干扰线条和噪点
for ($i = 0; $i < 5; $i++) {
imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255))); // 生成干扰线条

imagesetpixel($image, rand(0, $width), rand(0, $height), imagecolorallocate($image, rand(-255, 255), rand(-255, 255), rand(-255, 255))); // 生成噪点
// 在图像上绘制验证码字符并输出图像
$textColor = imagecolorallocate($image, 0, 0, 0); // 黑色字体颜色
for ($i = 0; $i < strlen($random_code); $i++) {
imagechar($image, 30, ($height / ($length - 1)) * $i + ($height / 4), $random_code[$i], $textColor); // 在图像上绘制字符,可以根据需要调整字体大小和位置偏移量
header(’Content-type: image/png’); // 设置输出图像类型为PNG格式
imagepng($image); // 输出图像到浏览器或保存到文件
imagedestroy($image); // 销毁图像资源以释放内存空间
?>
这段代码将生成一个包含随机验证码的PNG格式图像,并将其输出到浏览器或保存到文件中,验证码保存在会话中,以便后续验证用户输入,你可以根据需要调整验证码长度、图像大小、颜色和干扰线条的数量等参数。





