PHP实现路由的核心在于统一入口文件(如index.php),通过服务器重写规则拦截所有请求,解析REQUEST_URI路径,匹配HTTP方法与注册路由,支持静态与动态参数分发至对应控制器或回调函数。

PHP实现路由的核心在于拦截所有请求,统一入口,再根据URL路径分发到对应处理逻辑。最常见的做法是使用单一入口文件(如 index.php),结合服务器重写规则,将所有请求导向该文件,由PHP解析URI并调用相应控制器或回调函数。
一个基础的PHP路由系统包含以下几个关键点:
以下是一个轻量级的手动路由实现:
// index.php
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
<p>if ($uri === '/user') {
include 'controllers/user.php';
} elseif ($uri === '/post') {
include 'controllers/post.php';
} elseif ($uri === '/') {
echo "首页";
} else {
http_response_code(404);
echo "页面未找到";
}</p>这种方式适合小型项目,但扩展性差。可以进一步优化为数组注册式路由:
立即学习“PHP免费学习笔记(深入)”;
$routes = [
'GET /' => 'HomeController@index',
'GET /user' => 'UserController@list',
'POST /user' => 'UserController@create',
];
<p>$method = $_SERVER['REQUEST_METHOD'];
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);</p><p>$key = "$method $path";</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/1626">
<img src="https://img.php.cn/upload/ai_manual/000/000/000/175680270981990.jpg" alt="FashionLabs">
</a>
<div class="aritcle_card_info">
<a href="/ai/1626">FashionLabs</a>
<p>AI服装模特、商品图,可商用,低价提升销量神器</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="FashionLabs">
<span>38</span>
</div>
</div>
<a href="/ai/1626" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="FashionLabs">
</a>
</div>
<p>if (array_key_exists($key, $routes)) {
list($controller, $action) = explode('@', $routes[$key]);
require "controllers/$controller.php";
call_user_func([new $controller, $action]);
} else {
http_response_code(404);
echo "Not Found";
}</p>为了让路由生效,需配置服务器隐藏 index.php:
# .htaccess 文件(Apache)
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
Nginx 配置示例:
location / {
try_files $uri $uri/ /index.php?$query_string;
}
真实项目中常需要捕获变量,例如 /user/123:
$routes = [
'GET /user/(\d+)' => 'UserController@show',
];
<p>foreach ($routes as $pattern => $handler) {
list($method, $pathPattern) = explode(' ', $pattern, 2);
if ($_SERVER['REQUEST_METHOD'] !== $method) continue;</p><pre class='brush:php;toolbar:false;'>$regex = '#^' . str_replace('/', '\/', $pathPattern) . '$#';
if (preg_match($regex, $uri, $matches)) {
array_shift($matches); // 移除全匹配
list($controller, $action) = explode('@', $handler);
require "controllers/$controller.php";
call_user_func_array([new $controller, $action], $matches);
exit;
}}
基本上就这些。简单项目可手动实现,复杂应用建议使用框架(如 Laravel、Slim)内置路由,功能更完整,支持中间件、命名路由、分组等高级特性。核心思想不变:统一入口 + 路径解析 + 分发执行。不复杂但容易忽略细节,比如HTTP方法区分和正则转义。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号