蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 PHP 8.4 AJAX 实时搜索大小写无关匹配、渐进过滤与 XSS 转义实测

PHPWindows x64、PHP 8.4 本地 CLI 环境。explore-ajax-livesearch.php
explore-ajax-livesearch.php141 行
<?php
declare(strict_types=1);

$cases = [];

function add_case(array &$cases, string $name, mixed $expected, mixed $actual): void {
    $cases[] = [
        'name' => $name,
        'passed' => ($actual === $expected),
        'expected' => $expected,
        'actual' => $actual,
    ];
}

$linksXml = <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<pages>
  <link>
    <title>HTML a tag</title>
    <url>https://example.org/html/tag-a</url>
  </link>
  <link>
    <title>HTML br tag</title>
    <url>https://example.org/html/tag-br</url>
  </link>
  <link>
    <title>HTML DOM Document</title>
    <url>https://example.org/dom/document</url>
  </link>
  <link>
    <title>CSS background Property</title>
    <url>https://example.org/css/background</url>
  </link>
  <link>
    <title>PHP Date() Function</title>
    <url>https://example.org/php/date</url>
  </link>
  <link>
    <title>JavaScript Array Object</title>
    <url>https://example.org/js/array</url>
  </link>
</pages>
XML;

$tmpFile = tempnam(sys_get_temp_dir(), 'live_links_');
if ($tmpFile === false) {
    throw new RuntimeException('Failed to create temp file');
}

$liveSearch = static function (string $xmlPath, string $q): string {
    $xmlDoc = new DOMDocument();
    $xmlDoc->load($xmlPath);
    $links = $xmlDoc->getElementsByTagName('link');
    $hint = '';

    if (strlen($q) > 0) {
        for ($i = 0; $i < $links->length; $i++) {
            $titles = $links->item($i)->getElementsByTagName('title');
            $urls = $links->item($i)->getElementsByTagName('url');
            if ($titles->length > 0 && $urls->length > 0 && $titles->item(0)->nodeType === XML_ELEMENT_NODE) {
                $titleVal = $titles->item(0)->childNodes->item(0)?->nodeValue ?? '';
                $urlVal = $urls->item(0)->childNodes->item(0)?->nodeValue ?? '';
                if (stristr($titleVal, $q) !== false) {
                    $anchor = "<a href='" . htmlspecialchars($urlVal, ENT_QUOTES, 'UTF-8')
                        . "' target='_blank'>" . htmlspecialchars($titleVal, ENT_QUOTES, 'UTF-8') . '</a>';
                    $hint = ($hint === '') ? $anchor : ($hint . '<br />' . $anchor);
                }
            }
        }
    }
    return $hint === '' ? 'no suggestion' : $hint;
};

try {
    file_put_contents($tmpFile, $linksXml);

    // Case 1: Case-insensitive search for "html" and "HTML"
    $resLower = $liveSearch($tmpFile, 'html');
    $resUpper = $liveSearch($tmpFile, 'HTML');
    add_case(
        $cases,
        'livesearch_case_insensitive_html',
        [
            'case_insensitive_equal' => true,
            'match_count' => 3,
            'has_br_separator' => true,
        ],
        [
            'case_insensitive_equal' => ($resLower === $resUpper),
            'match_count' => substr_count($resLower, '<a href='),
            'has_br_separator' => (substr_count($resLower, '<br />') === 2),
        ]
    );

    // Case 2: Progressive narrowing & widening when typing/deleting characters
    $c1 = substr_count($liveSearch($tmpFile, 'H'), '<a href=');
    $c2 = substr_count($liveSearch($tmpFile, 'HTML'), '<a href=');
    $c3 = substr_count($liveSearch($tmpFile, 'HTML DOM'), '<a href=');
    add_case(
        $cases,
        'livesearch_narrowing_filter',
        ['count_h' => 4, 'count_html' => 3, 'count_html_dom' => 1],
        ['count_h' => $c1, 'count_html' => $c2, 'count_html_dom' => $c3]
    );

    // Case 3: Unmatched query and empty query return "no suggestion"
    add_case(
        $cases,
        'livesearch_no_suggestion',
        ['unmatched' => 'no suggestion', 'empty' => 'no suggestion'],
        ['unmatched' => $liveSearch($tmpFile, 'GraphQL'), 'empty' => $liveSearch($tmpFile, '')]
    );

    // Case 4: Escaped special characters in XML title/url prevent broken markup
    $specialXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><pages><link>"
        . "<title>HTML &amp; CSS &lt;Guide&gt;</title>"
        . "<url>https://example.org/search?a=1&amp;b=2</url>"
        . "</link></pages>";
    $tmpSpecial = tempnam(sys_get_temp_dir(), 'live_esc_');
    try {
        file_put_contents($tmpSpecial, $specialXml);
        $escapedRes = $liveSearch($tmpSpecial, 'Guide');
    } finally {
        if ($tmpSpecial !== false && is_file($tmpSpecial)) {
            unlink($tmpSpecial);
        }
    }
    add_case(
        $cases,
        'livesearch_xss_safe_output',
        "<a href='https://example.org/search?a=1&amp;b=2' target='_blank'>HTML &amp; CSS &lt;Guide&gt;</a>",
        $escapedRes
    );
} finally {
    if (is_file($tmpFile)) {
        unlink($tmpFile);
    }
}

echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
本例需在 Windows x64、PHP 8.4 本地 CLI 环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、PHP 8.4 本地 CLI 环境。

入口文件:projects/php-ajax-livesearch-lab/explore-ajax-livesearch.php

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-ajax-livesearch.php,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、PHP 8.4 本地 CLI 环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:PHP

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

下载课程关联工程包:PHP

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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