蓝色天空.知识 · 实践 · 创造
我的收藏
PHP 教程目录 95章
课程介绍
PHP / LEARN BY DOING

PHP 表单验证

深入讲解 PHP 表单安全防护:$_SERVER["PHP_SELF"] 的跨站脚本(XSS)利用路径、htmlspecialchars() 实体转义规则、test_input() 清洗管线与 REQUEST_METHOD 判定。

学完这一章,你能够

  • 深入讲解 PHP 表单安全防护:$_SERVER["PHP_SELF"] 的跨站脚本(XSS)利用路径、htmlspecialchars() 实体转义规则、test_input() 清洗管线与 REQUEST_METHOD 判定。

表单安全背景与字段规则

处理客户端提交的表单数据时必须优先防范恶意脚本注入与垃圾数据。本节以包含名字、E-mail、网址、备注文本域及性别单选按钮的综合表单为例,明确各字段的必填与格式校验规则(见下方规则表与提示表)。

在纯 HTML 结构中,名字、E-mail 与网址使用 `<input type="text">`,备注使用 `<textarea rows="5" cols="40">`,性别使用同 `name="gender"` 的两个 `<input type="radio">`;`<form>` 采用 `method="post"` 并将 `action` 设为 `htmlspecialchars($_SERVER["PHP_SELF"])`——`$_SERVER["PHP_SELF"]` 返回相对网站根目录的当前脚本路径,从而把数据提交回当前页处理。

htmlspecialchars() 与 $_SERVER["PHP_SELF"] 的 XSS 防护

`htmlspecialchars()` 负责把五个 HTML 预定义字符转义为安全实体:`&` 转为 `&amp;`、`"` 转为 `&quot;`、`'` 在启用 `ENT_QUOTES`(PHP 8.1+ 默认包含 `ENT_QUOTES | ENT_SUBSTITUTE`)时转为 `&#039;`、`<` 转为 `&lt;`、`>` 转为 `&gt;`。本站 PHP 8.4.27 实测逐一验证全部 5 个字符转义结果完全一致。

若直接把未转义的 `$_SERVER["PHP_SELF"]` 写入 `action` 属性,攻击者在 URL 路径后拼接 `/"%3E%3Cscript%3Ealert('hacked')%3C/script%3E` 时,浏览器会提前闭合引号并解析执行注入的 `<script>` 标签——这就是典型的跨站脚本攻击(XSS),可能窃取表单数据、篡改全局变量或劫持重定向。

用 `htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, 'UTF-8')` 包裹 `action` 后,上述攻击载荷会被转义为 `/test_form.php/&quot;&gt;&lt;script&gt;alert(&#039;hacked&#039;)&lt;/script&gt;`,引号与尖括号均失去标签语法作用。本站实测未转义标签包含 `<script>`(`true`),转义后完全消除(`false`)。

test_input() 过滤管线与 POST 提交判定

除了防护 `action` 属性,所有用户输入也应先经统一过滤再进入页面展示:例如提交 `<script>location.href='https://example.org'</script>` 会被 `htmlspecialchars()` 转为无害实体字符串。标准清洗函数 `test_input()` 依次执行 `trim()` 去除首尾空白/制表符/换行、`stripslashes()` 去除反斜杠,以及 `htmlspecialchars()` 完成实体编码。本站实测输入 `" \tO\\'Reilly <b>&</b> \"PHP\" \r\n"` 经三步清洗后输出 `O&#039;Reilly &lt;b&gt;&amp;&lt;/b&gt; &quot;PHP&quot;`。

服务端通过判断 `$_SERVER["REQUEST_METHOD"] == "POST"` 识别表单是否已提交:首次 `GET` 访问跳过清洗并保持各变量为空字符串;`POST` 提交时逐项调用 `test_input()` 清洗。本站实测 `GET` 下 5 个字段全为空,`POST` 下 5 个字段均完成首尾去空与脚本转义。当前脚本仍允许字段留空,下一节将引入必需字段校验。

表单安全性提示

提示主题核心要点
表单数据安全处理任何客户端提交的数据都不可直接信任,必须通过服务端校验与输出转义防范脚本注入及垃圾信息。

综合表单字段验证规则

字段验证规则
名字必需;仅允许包含英文字母与空格
E-mail必需;须为合法电子邮件地址格式(包含 @ 与域名后缀)
网址可选;填写时须符合有效 URL 语法
备注可选;多行文本域(textarea)
性别必需;须从单选按钮中选中一项

$_SERVER["PHP_SELF"] 说明

概念说明
$_SERVER["PHP_SELF"] 作用超全局数组元素,返回相对文档根目录的当前执行脚本路径,常用于表单自提交,但输出到 HTML 时必须转义。

htmlspecialchars() 字符实体转换说明

函数转义行为
htmlspecialchars()将 &、"、'、<、> 五类特殊字符转换为 &amp;、&quot;、&#039;、&lt;、&gt;,防止浏览器将其误解析为 HTML/脚本标签。

跨站脚本攻击(XSS)说明

术语风险机制
XSS(Cross-Site Scripting)攻击者向网页输出中注入恶意 HTML 或 JavaScript 代码,其他用户访问该页时脚本在浏览器端执行,导致会话窃取或页面篡改。

运行 PHP_SELF XSS 转义、五字符实体编码、test_input 清洗与 POST 分发实验

含完整源码 · 130 行
展开查看收起
php
<?php
declare(strict_types=1);

function test_input(string $data): string
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
    return $data;
}

$cases = [];

// Case 1: PHP_SELF XSS attack vs htmlspecialchars mitigation
(function () use (&$cases): void {
    $craftedPhpSelf = '/test_form.php/"><script>alert(\'hacked\')</script>';
    $unsafeFormTag = '<form method="post" action="' . $craftedPhpSelf . '">';
    $safeFormTag = '<form method="post" action="' . htmlspecialchars($craftedPhpSelf, ENT_QUOTES, 'UTF-8') . '">';
    $actual = [
        'unsafe_contains_script_tag' => str_contains($unsafeFormTag, '<script>'),
        'safe_contains_script_tag' => str_contains($safeFormTag, '<script>'),
        'safe_form_tag' => $safeFormTag,
    ];
    $expected = [
        'unsafe_contains_script_tag' => true,
        'safe_contains_script_tag' => false,
        'safe_form_tag' => '<form method="post" action="/test_form.php/&quot;&gt;&lt;script&gt;alert(&#039;hacked&#039;)&lt;/script&gt;">',
    ];
    $cases[] = [
        'name' => 'php_self_xss_escape',
        'passed' => $actual === $expected,
        'expected' => $expected,
        'actual' => $actual,
    ];
})();

// Case 2: Five predefined HTML entities in htmlspecialchars(ENT_QUOTES)
(function () use (&$cases): void {
    $chars = ['&', '"', "'", '<', '>'];
    $mapped = [];
    foreach ($chars as $ch) {
        $mapped[$ch] = htmlspecialchars($ch, ENT_QUOTES, 'UTF-8');
    }
    $scriptInput = "<script>location.href='https://example.org'</script>";
    $actual = [
        'entities' => $mapped,
        'escaped_script' => htmlspecialchars($scriptInput, ENT_QUOTES, 'UTF-8'),
    ];
    $expected = [
        'entities' => [
            '&' => '&amp;',
            '"' => '&quot;',
            "'" => '&#039;',
            '<' => '&lt;',
            '>' => '&gt;',
        ],
        'escaped_script' => '&lt;script&gt;location.href=&#039;https://example.org&#039;&lt;/script&gt;',
    ];
    $cases[] = [
        'name' => 'htmlspecialchars_five_entities',
        'passed' => $actual === $expected,
        'expected' => $expected,
        'actual' => $actual,
    ];
})();

// Case 3: test_input pipeline (trim -> stripslashes -> htmlspecialchars)
(function () use (&$cases): void {
    $raw = "  \tO\\'Reilly <b>&</b> \"PHP\" \r\n";
    $actual = [
        'after_trim' => trim($raw),
        'after_stripslashes' => stripslashes(trim($raw)),
        'after_test_input' => test_input($raw),
    ];
    $expected = [
        'after_trim' => "O\\'Reilly <b>&</b> \"PHP\"",
        'after_stripslashes' => "O'Reilly <b>&</b> \"PHP\"",
        'after_test_input' => 'O&#039;Reilly &lt;b&gt;&amp;&lt;/b&gt; &quot;PHP&quot;',
    ];
    $cases[] = [
        'name' => 'test_input_trim_stripslashes_escape',
        'passed' => $actual === $expected,
        'expected' => $expected,
        'actual' => $actual,
    ];
})();

// Case 4: REQUEST_METHOD dispatch (GET skips validation, POST cleans all 5 fields)
(function () use (&$cases): void {
    $handleRequest = static function (string $method, array $post): array {
        $name = $email = $gender = $comment = $website = '';
        if ($method === 'POST') {
            $name = test_input((string)($post['name'] ?? ''));
            $email = test_input((string)($post['email'] ?? ''));
            $website = test_input((string)($post['website'] ?? ''));
            $comment = test_input((string)($post['comment'] ?? ''));
            $gender = test_input((string)($post['gender'] ?? ''));
        }
        return compact('name', 'email', 'website', 'comment', 'gender');
    };
    $actual = [
        'get_initial' => $handleRequest('GET', ['name' => 'Ignored']),
        'post_cleaned' => $handleRequest('POST', [
            'name' => '  Alice Lin  ',
            'email' => " alice@example.org\n",
            'website' => 'https://example.org',
            'comment' => "Hello <script>x</script>",
            'gender' => 'female',
        ]),
    ];
    $expected = [
        'get_initial' => ['name' => '', 'email' => '', 'website' => '', 'comment' => '', 'gender' => ''],
        'post_cleaned' => [
            'name' => 'Alice Lin',
            'email' => 'alice@example.org',
            'website' => 'https://example.org',
            'comment' => 'Hello &lt;script&gt;x&lt;/script&gt;',
            'gender' => 'female',
        ],
    ];
    $cases[] = [
        'name' => 'request_method_post_dispatch',
        'passed' => $actual === $expected,
        'expected' => $expected,
        'actual' => $actual,
    ];
})();

echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
核对恶意 PHP_SELF 路径转义后不再含 <script>、5 个 HTML 字符实体映射、test_input 三步清洗结果及 GET/POST 分支行为。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1232.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:PHP

课程关联工程包(登记关联95章) · 含当前章节或实例 · mbskycom202612a1232.zip

下载课程关联工程包:PHP

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1250.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

htmlspecialchars() 属于 HTML 输出上下文的编码手段,能防范 XSS,但不能替代数据库参数化查询(PDO 预处理)防 SQL 注入;工程上应保持原始干净数据入库,在输出到 HTML 时再执行实体转义。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习