当前位置:首页 > PHP

php实现获取验证码

2026-02-27 15:04:39PHP

使用GD库生成验证码

在PHP中,GD库是生成验证码图像的常用工具。以下是一个基本实现:

<?php
session_start();
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image, 0, 0, $width, $height, $bgColor);

$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$code = '';
for ($i = 0; $i < 4; $i++) {
    $code .= $chars[rand(0, strlen($chars) - 1)];
}

$_SESSION['captcha'] = $code;

for ($i = 0; $i < strlen($code); $i++) {
    $color = imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150));
    imagettftext($image, 20, rand(-30, 30), 20 + $i * 25, 30, $color, 'arial.ttf', $code[$i]);
}

header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>

添加干扰元素增强安全性

为了提高验证码的安全性,可以添加干扰线和干扰点:

// 添加干扰线
for ($i = 0; $i < 5; $i++) {
    $color = imagecolorallocate($image, rand(100, 200), rand(100, 200), rand(100, 200));
    imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $color);
}

// 添加干扰点
for ($i = 0; $i < 200; $i++) {
    $color = imagecolorallocate($image, rand(150, 250), rand(150, 250), rand(150, 250));
    imagesetpixel($image, rand(0, $width), rand(0, $height), $color);
}

使用Composer包简化实现

可以使用现成的Composer包如gregwar/captcha简化验证码生成:

php实现获取验证码

安装包:

composer require gregwar/captcha

使用示例:

php实现获取验证码

<?php
require 'vendor/autoload.php';
session_start();

$builder = new Gregwar\Captcha\CaptchaBuilder;
$builder->build();

$_SESSION['captcha'] = $builder->getPhrase();

header('Content-type: image/jpeg');
$builder->output();
?>

验证码验证逻辑

在表单提交后验证验证码:

<?php
session_start();
if ($_POST['captcha'] === $_SESSION['captcha']) {
    // 验证码正确
} else {
    // 验证码错误
}
unset($_SESSION['captcha']); // 验证后销毁
?>

增加验证码难度

可以通过以下方式增加验证码难度:

// 使用更复杂的字符集
$chars = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';

// 增加字符数量
$length = 6; // 代替之前的4个字符

// 使用扭曲变形
$builder->setDistortion(true);

注意事项

确保服务器已安装GD库,可通过phpinfo()检查。对于字体文件,确保路径正确或使用系统字体。验证码生成脚本应单独保存为PHP文件,通过img标签引用:

<img src="captcha.php" onclick="this.src='captcha.php?'+Math.random()">

标签: 验证码php
分享给朋友:

相关文章

git php实现

git php实现

Git 与 PHP 的集成实现 使用 PHP 执行 Git 命令 通过 PHP 的 exec()、shell_exec() 或 passthru() 函数可以直接调用 Git 命令,适用于服务器端操作…

php记住密码怎么实现

php记住密码怎么实现

使用Cookie实现记住密码功能 在PHP中,可以通过设置Cookie来记住用户的登录状态。以下是一个简单的实现方式: // 用户登录验证成功后 if ($login_success) {…

php 实现无限分类

php 实现无限分类

无限分类的实现方法 无限分类通常用于构建多层级结构的数据,如商品分类、菜单管理等。以下是几种常见的实现方式: 邻接列表模型(Adjacency List) 这是最简单的实现方式,每个分类记录存储其父…

php 无限分类的实现

php 无限分类的实现

无限分类的实现方法 无限分类通常用于构建树形结构数据,如商品分类、多级菜单等。以下是几种常见的实现方式: 邻接列表模型(Adjacency List) 邻接列表是最简单的实现方式,通过在每个节点中存…

php 链表实现

php 链表实现

在 PHP 中实现链表可以通过类来模拟链表节点(Node)和链表(LinkedList)结构。以下是链表的完整实现示例,包含基础操作如插入、删除、遍历等。 链表节点类(Node) 链表的基本单元是节…

php redis 队列实现

php redis 队列实现

PHP Redis 队列实现 Redis 是一个高性能的键值存储系统,常被用作消息队列。以下是使用 PHP 和 Redis 实现队列的几种方法。 安装依赖 确保已安装 PHP Redis 扩展。可以…