
在PHP中,修改路由(也称为重定向或重写)是常见的需求,尤其是在构建Web应用时。以下是一个简单的示例,展示如何使用PHP修改路由。
示例:使用PHP修改路由
路由修改前
| 请求URL | 服务器处理方式 |
|---|---|
| /index.php?name=John | 执行index.php文件,并查询参数name,值为John |
路由修改后
| 请求URL | 服务器处理方式 |
|---|---|
| /user/John | 执行相应的处理逻辑,例如:显示John的用户信息 |
以下是一个简单的PHP脚本示例,展示如何实现路由修改:
```php
// 定义路由规则
$routes = [
'/user/(:any)' => 'userProfile',
'/about' => 'aboutUs',
];
// 获取当前请求的URL路径
$uri = $_SERVER['REQUEST_URI'];
// 遍历路由规则
foreach ($routes as $pattern => $handler) {
if (preg_match($pattern, $uri, $matches)) {
// 调用相应的处理函数
$handler($matches[1]);
exit;
}
}
// 如果没有匹配的路由,显示404页面
function notFound() {
header('HTTP/1.1 404 Not Found');
echo '404 Not Found';
}
// 用户资料处理函数
function userProfile($username) {
echo "





