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

如何实现PHP搜索框匹配手动创建页面的跳转功能

解决方案

方法一:纯JavaScript实现(无需后端)

直接在页面中添加事件监听,捕捉回车操作完成跳转:

修改后的完整代码

<h3>SEARCH HERE  </h3>
<h7 id="xxxnot" style="color:#FF0000; padding-left:3px;"> </h7>
</section>
<section>
  <label class="input"> <i class="icon-append icon-tag"></i>
  <input size="35" id="samplees" type="text" name="samplees" required="required">
  </label>
</section>

<script>
const searchInput = document.getElementById('samplees');

// 监听回车键按下事件
searchInput.addEventListener('keydown', function(e) {
  if (e.key === 'Enter') {
    const pageName = this.value.trim();
    if (pageName) {
      // 拼接目标页面URL并跳转,自动添加.php后缀
      window.location.href = `${pageName}.php`;
    } else {
      // 输入为空时显示提示
      document.getElementById('xxxnot').textContent = '请输入页面名称';
    }
  }
});
</script>

说明:用户输入页面名称后按回车,会直接跳转到对应名称的PHP页面;如果输入为空,红色提示栏会显示提醒文字。


方法二:PHP后端处理(支持页面存在性验证)

适合需要避免跳转到不存在页面的场景,通过PHP先验证目标页面是否存在:

1. 修改搜索页的HTML,添加表单

<h3>SEARCH HERE  </h3>
<h7 id="xxxnot" style="color:#FF0000; padding-left:3px;"> </h7>
</section>
<section>
  <form action="search.php" method="get">
    <label class="input"> <i class="icon-append icon-tag"></i>
    <input size="35" id="samplees" type="text" name="samplees" required="required">
    </label>
    <!-- 可选:添加提交按钮,用户也可以按回车提交 -->
    <button type="submit" style="margin-top: 8px;">跳转</button>
  </form>
</section>

2. 创建search.php处理页面

<?php
if (isset($_GET['samplees'])) {
    $pageName = trim($_GET['samplees']);
    // 过滤非法字符,防止路径遍历攻击
    $pageName = preg_replace('/[^a-zA-Z0-9_-]/', '', $pageName);
    $targetPage = $pageName . '.php';

    if (file_exists($targetPage)) {
        // 目标页面存在,执行跳转
        header("Location: $targetPage");
        exit;
    } else {
        // 页面不存在,显示提示并返回原页面
        echo "<script>
                document.getElementById('xxxnot').textContent = '页面不存在,请检查输入';
                window.history.back();
              </script>";
        exit;
    }
} else {
    // 没有输入内容,返回搜索页面
    header("Location: index.php"); // 替换为你的搜索页面URL
    exit;
}
?>

说明:

  • 用户提交表单后,PHP会先过滤输入中的非法字符(避免恶意路径访问),然后检查目标页面是否存在
  • 页面存在则跳转,不存在则在原页面显示红色提示并返回

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 02:25:21