<?php
session_start();
$w=44; $h=22;
$code = rand(1000,9999);// 随机生成4位数字验证码
$_SESSION['gif_captcha'] = $code;// 保存验证码到 session 中
header('Content-Type: image/gif');// 设置 MIME 类型为 image/gif
$im = imagecreate($w, $h);// 创建一张100x30像素的新图像
imagecolorallocate($im, 255, 255, 255);// 设置图像的背景色为白色
$text_color = imagecolorallocate($im, 0, 0, 0);// 设置图像的字体颜色为黑色
imagestring($im, 8, 4, 4, $code, $text_color);// 在图像中绘制验证码
for ($i = 0; $i < 3; $i++) { // 添加干扰线 3:线条数
$line_color = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255));
imageline($im, rand(0, $w), rand(0, $h), rand(0, $w), rand(0, $h), $line_color);
}
for ($i = 0; $i < 30; $i++) { // 添加干扰点 30:点数
$pixel_color = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255));
imagesetpixel($im, rand(0, $w), rand(0, $h), $pixel_color);
}
imagegif($im);// 输出图像
imagedestroy($im);// 销毁图像
?>
为什么图片验证码使用纯数字,因为全球通用甚至文盲也会。