当前位置:首页 > PHP

php验证码的实现

2026-02-27 11:43:35PHP

PHP验证码的实现方法

使用GD库生成基础验证码

创建一个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';
$code = substr(str_shuffle($chars), 0, 6);
$_SESSION['captcha'] = $code;

// 添加干扰元素
for ($i = 0; $i < 10; $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 < 6; $i++) {
    $color = imagecolorallocate($image, rand(0, 100), rand(0, 100), rand(0, 100));
    imagettftext($image, 18, rand(-15, 15), 10 + $i * 20, 30, $color, 'arial.ttf', $code[$i]);
}

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

在HTML表单中使用验证码

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

验证用户输入

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

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

增强安全性措施

使用更复杂的干扰元素:

// 在captcha.php中添加
for ($i = 0; $i < 100; $i++) {
    $color = imagecolorallocatealpha($image, rand(0, 255), rand(0, 255), rand(0, 255), 70);
    imagesetpixel($image, rand(0, $width), rand(0, $height), $color);
}

使用现代验证码库

考虑使用gregwar/captcha等Composer包:

composer require gregwar/captcha

实现代码:

<?php
require 'vendor/autoload.php';
session_start();

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

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

防止自动化攻击

添加验证码尝试次数限制:

// 在submit.php中
if (!isset($_SESSION['attempts'])) {
    $_SESSION['attempts'] = 0;
}
$_SESSION['attempts']++;
if ($_SESSION['attempts'] > 3) {
    die("尝试次数过多");
}

php验证码的实现

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

相关文章

php实现分页

php实现分页

PHP实现分页的基本方法 使用原生PHP实现分页功能需要结合数据库查询和HTML展示。以下是核心实现步骤: 数据库查询与分页逻辑 // 连接数据库 $conn = new mysqli('lo…

php 实现文件下载

php 实现文件下载

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

php实现文件的下载

php实现文件的下载

PHP 实现文件下载的方法 在 PHP 中实现文件下载功能通常需要设置正确的 HTTP 头信息,并输出文件内容。以下是几种常见的实现方式: 使用 header() 函数强制下载 通过设置 Cont…

php实现分类

php实现分类

PHP实现分类的方法 数据库设计 创建分类表时,通常需要包含id、名称、父级id等字段。父级id用于实现多级分类结构。 CREATE TABLE categories ( id INT AU…

php实现的分页

php实现的分页

PHP 实现分页的方法 基本分页逻辑 分页的核心在于计算总页数、当前页码以及数据偏移量。假设每页显示 10 条数据: $current_page = isset($_GET['page']) ?…

php搜索功能实现的

php搜索功能实现的

PHP 搜索功能实现方法 数据库搜索实现 使用 SQL 的 LIKE 语句进行模糊匹配,适用于小型网站和简单搜索需求。 $searchTerm = $_GET['search']; $query =…