当前位置:首页 > PHP

php 实现验证码

2026-04-02 20:29:47PHP

使用 PHP 生成验证码

验证码(CAPTCHA)是一种用于区分人类用户和机器自动程序的工具。以下是使用 PHP 生成验证码的详细方法。

php 实现验证码

创建验证码图像

使用 PHP 的 GD 库生成验证码图像。确保服务器已安装 GD 库。

php 实现验证码

<?php
session_start();

// 设置验证码参数
$width = 120;
$height = 40;
$length = 6;
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';

// 创建图像
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);

// 生成随机验证码
$code = '';
for ($i = 0; $i < $length; $i++) {
    $code .= $chars[rand(0, strlen($chars) - 1)];
}

// 存储验证码到 Session
$_SESSION['captcha'] = $code;

// 添加干扰元素
for ($i = 0; $i < 5; $i++) {
    $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), $color);
}

// 绘制验证码文本
for ($i = 0; $i < $length; $i++) {
    $color = imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150));
    imagettftext($image, rand(18, 22), rand(-30, 30), 20 + $i * 20, 30, $color, 'arial.ttf', $code[$i]);
}

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

在 HTML 中调用验证码

将验证码图像嵌入到 HTML 表单中,用户提交表单时验证输入。

<form action="submit.php" method="post">
    <label for="captcha">验证码:</label>
    <input type="text" name="captcha" id="captcha" required>
    <img src="captcha.php" alt="验证码" onclick="this.src='captcha.php?'+Math.random()">
    <button type="submit">提交</button>
</form>

验证用户输入

在表单提交处理页面(如 submit.php)中验证用户输入的验证码是否匹配。

<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $userCaptcha = isset($_POST['captcha']) ? trim($_POST['captcha']) : '';
    $sessionCaptcha = isset($_SESSION['captcha']) ? $_SESSION['captcha'] : '';

    if (empty($userCaptcha) || $userCaptcha !== $sessionCaptcha) {
        die('验证码错误!');
    }

    // 验证通过,继续处理表单
    echo '验证码正确!';
}
?>

增强验证码安全性

  1. 限制验证码有效期:在 Session 中存储生成时间,验证时检查是否过期。
  2. 增加复杂度:使用更多干扰线、噪点或扭曲文本。
  3. 防止暴力破解:限制验证码尝试次数。
// 存储验证码生成时间
$_SESSION['captcha_time'] = time();

// 验证时检查时间(例如 5 分钟内有效)
if (time() - $_SESSION['captcha_time'] > 300) {
    die('验证码已过期!');
}

通过以上方法,可以快速实现一个基本的 PHP 验证码功能,并根据需求进一步优化安全性。

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

相关文章

php实现登录

php实现登录

PHP 登录功能实现 数据库连接与用户表创建 创建一个数据库连接文件 db.php,用于管理数据库连接。MySQL 示例代码如下: <?php $host = 'localhost'; $db…

php实现聊天

php实现聊天

实现 PHP 聊天功能的方法 使用 WebSocket 和 PHP 实现实时聊天 WebSocket 是一种全双工通信协议,适合实现实时聊天功能。PHP 可以通过 Ratchet 库实现 WebSo…

php实现接口

php实现接口

PHP 实现接口的方法 在 PHP 中,接口(Interface)用于定义一组方法的规范,而不实现具体功能。类可以实现一个或多个接口,并必须实现接口中定义的所有方法。 定义接口 接口使用 inter…

php 实现秒杀

php 实现秒杀

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

php实现的进度条

php实现的进度条

PHP 实现的进度条方法 在 PHP 中实现进度条通常可以通过命令行脚本(CLI)或 Web 页面两种方式完成。以下是几种常见的实现方法: 命令行进度条 使用 PHP CLI 实现进度条,可以通过不…

php 实现面包屑导航

php 实现面包屑导航

实现面包屑导航的方法 面包屑导航(Breadcrumb Navigation)是一种常见的网站导航方式,用于显示用户当前页面的路径。以下是几种在 PHP 中实现面包屑导航的方法。 基于 URL 路径…