当前位置:首页 > PHP

php实现验证码

2026-02-27 10:33:05PHP

生成验证码图片

使用 PHP 的 GD 库创建验证码图片。需要确保服务器已安装 GD 库扩展。

// 创建画布
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);

// 设置背景色和文字颜色
$bgColor = imagecolorallocate($image, 255, 255, 255);
$textColor = imagecolorallocate($image, 0, 0, 0);

// 填充背景
imagefilledrectangle($image, 0, 0, $width, $height, $bgColor);

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

// 将验证码写入图片
imagettftext($image, 20, 0, 10, 30, $textColor, 'arial.ttf', $code);

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

// 输出图片
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);

存储验证码

将生成的验证码存储在会话中,以便后续验证。

php实现验证码

session_start();
$_SESSION['captcha'] = $code;

验证用户输入

创建表单接收用户输入并与会话中的验证码比对。

session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $userInput = $_POST['captcha'] ?? '';
    if (strtoupper($userInput) === strtoupper($_SESSION['captcha'])) {
        echo '验证码正确';
    } else {
        echo '验证码错误';
    }
    unset($_SESSION['captcha']);
}

前端集成

在HTML表单中添加验证码图片和输入框。

php实现验证码

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

提高安全性

增加验证码的复杂度以提高安全性。

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

// 添加扭曲效果
function distortImage($image) {
    $width = imagesx($image);
    $height = imagesy($image);
    $temp = imagecreatetruecolor($width, $height);
    imagecopy($temp, $image, 0, 0, 0, 0, $width, $height);
    for ($y = 0; $y < $height; $y++) {
        $shift = rand(-2, 2);
        imagecopy($image, $temp, 0, $y, $shift, $y, $width, 1);
    }
    imagedestroy($temp);
}

验证码过期设置

为验证码设置有效期,通常为5-10分钟。

$_SESSION['captcha_time'] = time();
// 验证时检查时间
if (time() - $_SESSION['captcha_time'] > 600) {
    echo '验证码已过期';
}

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

相关文章

php实现分页

php实现分页

PHP实现分页的基本方法 使用LIMIT和OFFSET进行数据库查询分页。通过计算当前页码和每页显示数量,动态生成SQL语句。 $page = isset($_GET['page']) ? (int…

php实现文件下载

php实现文件下载

PHP实现文件下载的方法 通过PHP实现文件下载功能,可以采用多种方式,以下是几种常见的实现方法: 使用header()函数强制下载 设置HTTP头信息,强制浏览器下载文件而非直接打开: $fi…

php实现图片上传

php实现图片上传

实现图片上传的基本步骤 创建HTML表单用于文件上传,表单需设置enctype="multipart/form-data"属性,确保文件数据正确传输。 <form action="uploa…

php实现搜索

php实现搜索

PHP实现搜索功能的方法 在PHP中实现搜索功能通常涉及数据库查询和用户输入的匹配。以下是几种常见的实现方式: 使用MySQL LIKE语句 通过简单的LIKE语句实现基础搜索: $searc…

php 实现接口

php 实现接口

PHP 实现接口的方法 在 PHP 中,接口(Interface)用于定义一组方法的规范,而不包含具体的实现。类可以实现(implement)接口,并必须实现接口中定义的所有方法。 定义接口 接口…

php实现异步

php实现异步

PHP 实现异步的方法 PHP 本身是同步执行的脚本语言,但可以通过以下方法模拟异步操作或实现异步效果: 使用多进程(pcntl_fork) 通过 pcntl_fork 创建子进程实现异步,适用于…