以下是一个使用PHP和GD库生成和处理图形验证码的示例代码:
<?php// 创建一个验证码图像$width = 200;$height = 50;$image = imagecreatetruecolor($width, $height);// 创建白色背景$bg_color = imagecolorallocate($image, 255, 255, 255);imagefill($image, 0, 0, $bg_color);// 生成随机验证码文本$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';$code = '';for ($i = 0; $i < 6; $i++) { $code .= $chars[rand(0, strlen($chars) - 1)];}// 将验证码文本保存到session中session_start();$_SESSION['captcha_code'] = $code;// 将验证码文本绘制到图像中$text_color = imagecolorallocate($image, 0, 0, 0);imagettftext($image, 20, 0, 10, 30, $text_color, 'arial.ttf', $code);// 添加干扰线for ($i = 0; $i < 10; $i++) { $line_color = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255)); imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $line_color);}// 输出验证码图像header('Content-type: image/png');imagepng($image);// 释放内存imagedestroy($image);?>您可以将上面的代码保存为一个PHP文件,然后在需要显示验证码的页面上引用该文件的URL来显示验证码图像。当用户提交表单时,您可以通过比对用户输入的验证码和session中保存的验证码来验证验证码是否正确。
请注意,上面的代码中使用了imagettftext函数来绘制验证码文本,因此您需要确保服务器上安装了GD库和FreeType支持。您还需要提供一个TrueType字体文件(比如arial.ttf)来用于绘制文本。您可以在网上找到免费的TrueType字体文件来使用。




