PHP 验证码生成与显示
以下是一个完整的PHP验证码实现方案,包括生成验证码图片和验证用户输入的功能。
1. 创建验证码生成文件 (captcha.php)
php
session_start();
// 验证码配置
$width = 120; // 图片宽度
$height = 40; // 图片高度
$length = 6; // 验证码长度
$bg_color = '#f3f3f3'; // 背景颜色
// 创建图像
$image = imagecreatetruecolor($width, $height);
// 设置背景色
$bg = hex2rgb(';
$bg_color = imagecolorallocate($image, $bg['red'], $bg['green'], $bg['blue']);
imagefill($image, 0, 0, $bg_color);
// 生成随机验证码
$chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= $chars[rand(0, strlen($chars) - 1)];
// 存储验证码到session
$_SESSION['captcha'] = strtolower($code);
// 添加干扰线
for ($i = 0; $i < 5; $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);
// 添加干扰点
for ($i = 0; $i < 100; $i++) {
$pixel_color = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
imagesetpixel($image, rand(0, $width), rand(0, $height), $pixel_color);
// 写入验证码文字
$text_color = imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150));
$font = 5; // 使用内置字体
// 计算字符位置
$text_width = imagefontwidth($font) * $length;
$x = ($width - $text_width) / 2;
$y = ($height - imagefontheight($font)) / 2;
// 写入每个字符(稍微错开位置增加难度)
for ($i = 0; $i < $length; $i++) {
$char_color = imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150));
imagestring($image, $
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.