
本文详解PHP手动路由中因$_SERVER['PATH_INFO']不可靠导致“Page not found”错误的根本原因,并提供兼容性更强的路径解析方法及完整可运行路由实现。
本文详解php手动路由中因`$_server['path_info']`不可靠导致“page not found”错误的根本原因,并提供兼容性更强的路径解析方法及完整可运行路由实现。
在基于PHP的手动路由实践中,初学者常误用 $_SERVER['PATH_INFO'] 作为路径匹配依据,但该变量仅在启用 CGI/FastCGI 模式且 Web 服务器(如 Apache/Nginx)显式配置支持 PATH_INFO 的情况下才可靠存在。默认 XAMPP/MAMP 或多数 Nginx 配置中,访问 http://localhost/Project/index.php/ 实际不会触发 PATH_INFO 设置,导致路由匹配始终失败,最终输出 “Sorry! Page not found”。
更健壮的做法是直接从 $_SERVER['REQUEST_URI'] 提取原始请求路径(去除查询参数),再进行路由匹配。以下是优化后的完整实现:
// routes.php
<?php $routes = [
'/' => 'controller/mainpagecontroller.php',
'/addpost' => 'controller/addpostcontroller.php',
];
function getRequestPath(): string {
$uri = $_SERVER['REQUEST_URI'] ?? '/';
$pos = strpos($uri, '?');
return $pos === false ? $uri : substr($uri, 0, $pos);
}
function router(array $routes): void {
$requestPath = rtrim(getRequestPath(), '/');
foreach ($routes as $path => $target) {
// 支持根路径 '/' 和子路径如 '/addpost'
$normalizedPath = rtrim($path, '/');
if ($requestPath === $normalizedPath) {
if (file_exists($target)) {
require $target;
return;
}
http_response_code(404);
echo 'Error: Controller file not found — ' . htmlspecialchars($target);
return;
}
}
http_response_code(404);
echo 'Sorry! Page not found';
}
router($routes);
?>
同时,需确保 index.php 正确引入路由逻辑(而非仅加载数据库引导):
开箱即用的技能链路由引擎。13 条预定义链覆盖搜索、开发、审查、MLOps、法律、创意等场景,三层路由架构(触发词→SAD反馈→DAG编排),recall@10=96.97%。配置驱动(chains.yaml),零代码扩展。pip install skill-weave-chains 一键安装。
<!-- index.php --> <?php require 'routes.php'; // 替换原 db/bootstrap.php 的引入位置 // 若仍需数据库连接,应在 controller 中按需引入,避免全局加载 ?>
⚠️ 关键注意事项:
- 不要使用 header("Location: ...") 进行内部路由跳转——这会发起 HTTP 重定向,暴露真实文件路径且破坏单入口模式;应改用 require 或 include 直接加载控制器;
- 所有控制器文件(如 mainpagecontroller.php)应为纯 PHP/HTML 模板,不包含 ,避免头部已发送错误;
- 路由路径建议统一以 / 开头并标准化结尾斜杠处理(如 rtrim()),提升匹配鲁棒性;
- 生产环境务必禁用 display_errors,并通过 http_response_code(404) 显式返回标准错误状态。
通过以上重构,访问 http://localhost/Project/index.php/ 或 http://localhost/Project/index.php(取决于 Web 服务器重写配置)均可正确加载首页控制器,彻底解决“Page not found”问题,为后续扩展 RESTful 路由打下坚实基础。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










