You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置需验证Captcha方可加载网页的PHP本地实现方案?

本地PHP验证码保护链接实现方案

这个方案完全基于本地PHP实现,无需依赖第三方服务,包含链接生成、验证码验证、保护链接删除三个核心功能,满足你对链接保护的需求。

核心文件结构

  • index.php:链接生成与管理界面
  • verify.php:验证码验证与跳转页面
  • captcha.php:生成验证码图片
  • links.txt:存储保护链接与原始链接的映射(需提前设置服务器可写权限)
  • delete.php:处理保护链接的删除请求

1. 链接生成与管理页面(index.php)

<?php
// 初始化链接存储文件
$linksFile = 'links.txt';
if (!file_exists($linksFile)) {
    file_put_contents($linksFile, '');
}

// 处理生成保护链接请求
$protectedLink = '';
$deleteLink = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['original_url'])) {
    $originalUrl = trim($_POST['original_url']);
    // 生成唯一标识
    $token = uniqid('', true);
    // 存储映射关系:token|original_url
    file_put_contents($linksFile, $token . '|' . $originalUrl . PHP_EOL, FILE_APPEND);
    // 生成保护链接和删除链接
    $protectedLink = 'verify.php?token=' . $token;
    $deleteLink = 'delete.php?token=' . $token;
}

// 读取已生成的保护链接列表
$existingLinks = [];
$lines = file($linksFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
    list($token, $url) = explode('|', $line, 2);
    $existingLinks[] = [
        'protected' => 'verify.php?token=' . $token,
        'delete' => 'delete.php?token=' . $token,
        'original' => $url
    ];
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>生成验证码保护链接</title>
    <style>
        .link-item { margin: 10px 0; padding: 10px; border: 1px solid #eee; }
        input[type="url"] { width: 300px; padding: 8px; margin-right: 8px; }
        button { padding: 8px 16px; }
    </style>
</head>
<body>
    <h2>生成带验证码保护的链接</h2>
    <form method="post">
        <input type="url" name="original_url" placeholder="输入需要保护的链接" required>
        <button type="submit">生成保护链接</button>
    </form>

    <?php if ($protectedLink): ?>
    <div class="link-item">
        <p>生成的保护链接:<a href="<?php echo $protectedLink; ?>"><?php echo $protectedLink; ?></a></p>
        <p>删除该保护:<a href="<?php echo $deleteLink; ?>" onclick="return confirm('确定要删除这个保护链接吗?')">删除链接</a></p>
    </div>
    <?php endif; ?>

    <h3>已生成的保护链接</h3>
    <?php if (empty($existingLinks)): ?>
    <p>暂无已生成的保护链接</p>
    <?php else: ?>
        <?php foreach ($existingLinks as $link): ?>
        <div class="link-item">
            <p>原始链接:<?php echo $link['original']; ?></p>
            <p>保护链接:<a href="<?php echo $link['protected']; ?>"><?php echo $link['protected']; ?></a></p>
            <p>删除:<a href="<?php echo $link['delete']; ?>" onclick="return confirm('确定要删除吗?')">删除</a></p>
        </div>
        <?php endforeach; ?>
    <?php endif; ?>
</body>
</html>

2. 验证码验证页面(verify.php)

<?php
session_start();
$linksFile = 'links.txt';

// 检查token是否存在
if (empty($_GET['token'])) {
    die('无效的请求');
}
$token = $_GET['token'];

// 查找对应的原始链接
$originalUrl = false;
$lines = file($linksFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
    list($storedToken, $url) = explode('|', $line, 2);
    if ($storedToken === $token) {
        $originalUrl = $url;
        break;
    }
}
if (!$originalUrl) {
    die('该保护链接已失效');
}

// 处理验证码验证
$verified = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['captcha'])) {
    if (strtolower($_POST['captcha']) === strtolower($_SESSION['captcha_code'])) {
        // 验证成功,跳转到原始链接
        header('Location: ' . $originalUrl);
        exit;
    } else {
        $error = '验证码输入错误,请重试';
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>验证验证码</title>
    <style>
        .captcha-group { margin: 15px 0; }
        input[type="text"] { padding: 8px; margin-right: 8px; }
        button { padding: 8px 16px; }
        .error { color: red; }
    </style>
</head>
<body>
    <h2>请完成验证码验证以访问链接</h2>
    <?php if (isset($error)): ?>
    <p class="error"><?php echo $error; ?></p>
    <?php endif; ?>
    <form method="post">
        <div class="captcha-group">
            <img src="captcha.php" alt="验证码" onclick="this.src='captcha.php?' + Math.random()">
            <input type="text" name="captcha" placeholder="输入验证码" required>
        </div>
        <button type="submit">验证并访问</button>
    </form>
</body>
</html>

3. 验证码图片生成(captcha.php)

<?php
session_start();
// 生成随机4位字母数字验证码
$code = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'), 0, 4);
$_SESSION['captcha_code'] = $code;

// 创建验证码图片
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);

// 设置颜色
$bgColor = imagecolorallocate($image, 255, 255, 255);
$textColor = imagecolorallocate($image, 0, 0, 0);
$lineColor = imagecolorallocate($image, 150, 150, 150);

// 填充背景
imagefill($image, 0, 0, $bgColor);

// 添加干扰线
for ($i = 0; $i < 5; $i++) {
    imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $lineColor);
}

// 添加验证码文字(需确保服务器存在arial.ttf字体,可替换为本地已有的字体路径)
imagettftext($image, 20, rand(-5, 5), rand(10, $width-80), rand(25, $height-10), $textColor, 'arial.ttf', $code);

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

4. 保护链接删除页面(delete.php)

<?php
$linksFile = 'links.txt';

if (empty($_GET['token'])) {
    die('无效的请求');
}
$token = $_GET['token'];

// 读取所有链接,过滤掉要删除的token
$lines = file($linksFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$newLines = [];
foreach ($lines as $line) {
    list($storedToken) = explode('|', $line, 2);
    if ($storedToken !== $token) {
        $newLines[] = $line;
    }
}
// 重写文件
file_put_contents($linksFile, implode(PHP_EOL, $newLines));

// 跳转回管理页面
header('Location: index.php');
exit;
?>

使用说明

  1. 将所有文件上传至PHP环境的服务器目录,给links.txt设置可写权限(例如执行chmod 664 links.txt)
  2. 访问index.php,输入需要保护的链接,点击生成即可得到带验证码保护的链接
  3. 用户访问保护链接时,需输入正确的验证码才能跳转至原始链接
  4. 可通过生成的删除链接移除对应的保护规则

注意事项

  • 依赖PHP的GD库,需确保服务器已启用该扩展
  • 若使用自定义字体,需修改captcha.php中的字体路径
  • links.txt存储明文映射,如需更高安全性,可对链接进行加密存储
  • 验证码会话有效期取决于PHP的session配置,默认关闭浏览器后失效

内容的提问来源于stack exchange,提问作者user19918009

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:48:22