当前位置:首页 > 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中实现文件上传需要使用$_FILES超全局数组处理上传的文件数据。表单必须设置enctype="multipart/form-data"属性,并采用POST方法提交。 创…

php实现购物车

php实现购物车

PHP实现购物车功能 购物车功能是电商网站的核心模块之一,通常涉及商品添加、删除、数量修改和结算等操作。以下是使用PHP实现购物车功能的几种方法。 使用Session存储购物车数据 Session是…

php记住密码怎么实现

php记住密码怎么实现

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

php 购物车实现

php 购物车实现

数据库设计 购物车功能通常需要设计数据库表存储商品和用户信息。常见的表包括products(商品表)、users(用户表)和cart(购物车表)。cart表通常包含字段:id(主键)、user_id(…

php实现跳转

php实现跳转

PHP 实现页面跳转的方法 在 PHP 中实现页面跳转有多种方式,以下是常见的几种方法及其适用场景: 使用 header() 函数 通过 header() 函数发送 HTTP 头部信息实现跳转。注意…

php队列的实现

php队列的实现

PHP队列的实现方式 PHP中实现队列功能可以通过多种方式,根据需求选择适合的方案: 使用数组实现基础队列 PHP数组本身支持队列操作,利用array_push和array_shift函数: $q…