当前位置:首页 > PHP

php 实现验证码

2026-01-13 13:39:22PHP

使用 PHP 生成验证码

验证码(CAPTCHA)用于防止自动化脚本提交表单,以下是几种常见的 PHP 实现方法。

使用 GD 库生成图片验证码

GD 库是 PHP 的图像处理扩展,可用于生成验证码图片。

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

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

$font = 'path/to/font.ttf'; // 使用真实字体文件路径
for ($i = 0; $i < $length; $i++) {
    $color = imagecolorallocate($image, rand(0, 100), rand(0, 100), rand(0, 100));
    imagettftext($image, 20, rand(-30, 30), 10 + $i * 20, 30, $color, $font, $code[$i]);
}

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

添加干扰元素

为提高安全性,可以添加干扰线或干扰点。

php 实现验证码

// 添加干扰线
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 < 100; $i++) {
    $color = imagecolorallocate($image, rand(100, 200), rand(100, 200), rand(100, 200));
    imagesetpixel($image, rand(0, $width), rand(0, $height), $color);
}

验证用户输入

在表单提交后验证用户输入的验证码。

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

使用 Composer 包

对于更复杂的需求,可以使用现成的 Composer 包,如 gregwar/captcha

php 实现验证码

安装包:

composer require gregwar/captcha

使用示例:

<?php
require 'vendor/autoload.php';
use Gregwar\Captcha\CaptchaBuilder;

$builder = new CaptchaBuilder;
$builder->build();
$_SESSION['phrase'] = $builder->getPhrase();

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

验证时比较 $_SESSION['phrase'] 与用户输入。

安全注意事项

  • 验证码应包含大小写字母和数字,避免使用易混淆字符(如 0 和 O)
  • 验证码应在服务器端生成并存储,使用后立即销毁
  • 考虑限制验证码尝试次数防止暴力破解
  • 对于重要操作,可使用更复杂的验证码类型(如数学题、行为验证等)

这些方法提供了从基础到进阶的 PHP 验证码实现方案,可根据实际需求选择适合的方式。

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

相关文章

php实现验证码

php实现验证码

PHP实现验证码的方法 使用GD库生成验证码 GD库是PHP中处理图像的扩展,可用于生成验证码图片。 <?php session_start(); $width = 120; $height…

php实现定时任务

php实现定时任务

PHP 实现定时任务的几种方法 在 PHP 中实现定时任务可以通过多种方式完成,具体选择取决于项目需求和服务器环境。以下是常见的实现方法: 使用 Cron 任务 Cron 是 Linux 系统中常…

php实现

php实现

PHP 实现的基本方法 PHP 是一种服务器端脚本语言,广泛用于 Web 开发。以下是 PHP 实现的一些常见方法。 变量与数据类型 PHP 变量以 $ 开头,支持多种数据类型: $nam…

php 实现文件下载

php 实现文件下载

实现文件下载的基本方法 使用 PHP 实现文件下载的核心是通过设置 HTTP 头部信息,强制浏览器将文件作为附件下载而非直接显示。以下是一个基础实现示例: $file_path = '/path/…

php 实现秒杀

php 实现秒杀

PHP 实现秒杀的关键技术 秒杀系统需要解决高并发、超卖、性能瓶颈等问题。以下是实现秒杀的核心方案: 使用 Redis 预减库存 将商品库存提前加载到 Redis 中,通过原子操作保证库存准确性:…