現代 Web 應用常見的 RESTful 風格 URL(如 /module/show/action/list/page/7 或 /article/123.html)不僅美觀,更利於 SEO。本文提供一組輕量級函數,配合 Apache mod_rewrite,快速在 PHP 專案中落地友好 URL。
<?php
/**
* 解析 PATH_INFO,回傳合併後的 $_GET 陣列
* 支援格式:/module/show/action/list/page/7
*/
function getQueryString() {
// 移除開頭斜線,以 / 分段
$_SGETS = explode("/", substr($_SERVER['PATH_INFO'], 1));
$_SLEN = count($_SGETS);
$_SGET = $_GET; // 保留原有查詢字串參數
// 兩兩配對為 key/value
for ($i = 0; $i < $_SLEN; $i += 2) {
if (!empty($_SGETS[$i]) && !empty($_SGETS[$i + 1])) {
$_SGET[$_SGETS[$i]] = $_SGETS[$i + 1];
}
}
// 約定鍵名:m=模組(Controller), a=動作(Action)
$_SGET['m'] = !empty($_SGET['m']) && is_string($_SGET['m'])
? trim($_SGET['m']) . 'Action'
: 'indexAction';
$_SGET['a'] = !empty($_SGET['a']) && is_string($_SGET['a'])
? trim($_SGET['a'])
: 'run';
return $_SGET;
}
/**
* 根據陣列生成友好 URL 字串
* 需配合全域設定 $Global['urlmode'] 與 $Global['urlsuffix']
*/
function setUrl($arr) {
global $Global;
$queryString = '';
if ($Global['urlmode'] == 2) { // 模式 2:PATH_INFO 風格
foreach ($arr as $k => $v) {
$queryString .= $k . '/' . $v . '/';
}
}
$queryString .= $Global['urlsuffix']; // 如 .html 或空字串
return $queryString;
}
?>
<?php
$_GET = getQueryString();
// 後續直接使用 $_GET['m'], $_GET['a'], $_GET['id'] ...
?>
預設會產生 /index.php/module/show/...,若想要 /module/show/...,需在網站根目錄建立 .htaccess:
RewriteEngine on
# 排除靜態資源與入口檔本身
RewriteCond $1 !^(index\.php|css|pics|themes|js|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]
<?php
$_GET = getQueryString();
print_r($_GET);
// 訪問 https://domain.com/module/show/action/list/page/7
// 輸出:Array ( [m] => moduleAction [a] => show [action] => list [page] => 7 )
?>
m/a 對應到具體 Controller/Action 類別,支援命名空間自動載入。int、布林字串轉 bool。PATH_INFO 最前段解析 lang 參數(/zh/module/...)。這套方案無需重型框架,幾十行代碼即可賦予專案現代化 URL 結構,適合中小型專案快速落地。