当前位置:首页 > PHP

php验证码实现

2026-02-27 11:18:27PHP

验证码生成与验证的实现

在PHP中实现验证码功能通常包括生成验证码图片和验证用户输入两部分。以下是完整的实现方法:

生成验证码图片

创建名为captcha.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 = 4;
$captcha = '';
for ($i = 0; $i < $length; $i++) {
    $captcha .= $chars[rand(0, strlen($chars) - 1)];
}
$_SESSION['captcha'] = $captcha;

// 添加干扰元素
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, 100), rand(0, 100), rand(0, 100));
    $fontSize = rand(16, 24);
    $x = ($width / $length) * $i + rand(5, 10);
    $y = rand($fontSize, $height - 5);
    imagettftext($image, $fontSize, rand(-15, 15), $x, $y, $color, 'arial.ttf', $captcha[$i]);
}

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

在HTML中显示验证码

在表单页面中插入验证码图片:

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

验证用户输入

创建submit.php文件处理表单验证:

<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $userCaptcha = strtoupper(trim($_POST['captcha']));
    $sessionCaptcha = $_SESSION['captcha'];

    if ($userCaptcha === $sessionCaptcha) {
        echo "验证码正确";
    } else {
        echo "验证码错误";
    }

    unset($_SESSION['captcha']); // 验证后清除
}
?>

安全性增强措施

使用更复杂的验证码字符集,避免使用易混淆的字符如0和O。增加验证码过期时间限制:

$_SESSION['captcha_time'] = time();
// 验证时检查是否超过5分钟
if (time() - $_SESSION['captcha_time'] > 300) {
    echo "验证码已过期";
}

对于生产环境,考虑使用Google reCAPTCHA等第三方服务提供更强大的验证码保护。

php验证码实现

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

相关文章

php实现栈

php实现栈

栈的基本概念 栈(Stack)是一种遵循后进先出(LIFO)原则的数据结构。核心操作包括: push:元素入栈。 pop:元素出栈(返回并移除栈顶元素)。 peek:查看栈顶元素…

php实现跳转

php实现跳转

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

php无限分类的实现

php无限分类的实现

PHP无限分类的实现 无限分类是一种常见的树形结构数据组织方式,适用于商品分类、菜单管理、地区选择等场景。以下是几种实现方法: 递归实现法 递归是最直观的实现方式,通过函数自身调用来遍历子分类。数…

php 实现排序

php 实现排序

PHP 实现数组排序的方法 PHP 提供了多种内置函数和方法来实现数组排序,适用于不同的排序需求。以下是一些常见的排序实现方式: 使用 sort() 函数对数组进行升序排序 sort() 函数对数组…

php 实现类

php 实现类

PHP 类的基本实现 在 PHP 中,类通过 class 关键字定义,后跟类名和一对花括号。类名通常遵循大驼峰命名法(如 ClassName)。以下是基本语法: class ClassName {…

php mvc 实现

php mvc 实现

PHP MVC 实现方法 MVC(Model-View-Controller)是一种设计模式,用于分离应用程序的逻辑、数据和界面。以下是实现PHP MVC框架的关键步骤。 目录结构 创建以下目录结构…