在 PHP 中,可以使用 GD 库来生成随机图片校验码。以下是一个简单的示例:
// 设置验证码长度和图片宽度、高度 $codeLength = 6; $imgWidth = 120; $imgHeight = 40; // 创建图像 $image = imagecreatetruecolor($imgWidth, $imgHeight); // 设置背景颜色和字体颜色 $bgColor = imagecolorallocate($image, 255, 255, 255); $textColor = imagecolorallocate($image, 0, 0, 0); // 填充背景色 imagefill($image, 0, 0, $bgColor); // 生成随机验证码 $code = ""; for ($i = 0; $i < $codeLength; $i++) { $code .= chr(mt_rand(97, 122)); } // 将验证码保存到 session 中 session_start(); $_SESSION['captcha'] = $code; // 将验证码绘制到图像中 $font = 5; $fontWidth = imagefontwidth($font); $fontHeight = imagefontheight($font); $x = ($imgWidth - $fontWidth * $codeLength) / 2; $y = ($imgHeight - $fontHeight) / 2; imagestring($image, $font, $x, $y, $code, $textColor); // 设置 HTTP 头信息,输出图像 header("Content-type: image/png"); imagepng($image); // 销毁图像 imagedestroy($image);
在上面的代码中,首先使用 imagecreatetruecolor() 函数创建一个指定宽度和高度的图像,然后使用 imagecolorallocate() 函数设置背景颜色和字体颜色。接着使用 imagefill() 函数将整个图像填充为背景颜色。
然后使用 mt_rand() 函数生成随机验证码,并将其保存到 session 中。最后使用 imagestring() 函数将验证码绘制到图像中,使用 header() 函数设置 HTTP 头信息,输出图像。最后使用 imagedestroy() 函数销毁图像,释放内存。
这只是一个简单的示例,实际应用中还需要考虑安全性等方面的问题。