解析 URL 參數是 Web 開發基礎操作。本文比較四種核心方法:`$_SERVER` 變數、`parse_url()`、`parse_str()`、`pathinfo()`,並延伸至路由解析、查詢字串建構、安全過濾等實戰技巧。
<?php
// 完整請求 URI(含查詢字串)
$requestUri = $_SERVER['REQUEST_URI']; // /path/to/page?name=value&foo=bar
// 僅查詢字串
$queryString = $_SERVER['QUERY_STRING']; // name=value&foo=bar
// 解析為陣列(需自行處理)
parse_str($queryString, $params);
// $params = ['name' => 'value', 'foo' => 'bar']
// 注意:$_SERVER['REQUEST_URI'] 包含路徑,$_SERVER['QUERY_STRING'] 不包含
將 URL 分解為結構化元件:scheme、host、port、user、pass、path、query、fragment。
<?php
$url = 'https://user:pass@example.com:8080/path/to/page?name=value&foo=bar#section';
$parts = parse_url($url);
/*
Array
(
[scheme] => https
[host] => example.com
[port] => 8080
[user] => user
[pass] => pass
[path] => /path/to/page
[query] => name=value&foo=bar
[fragment] => section
)
*/
// 組合基礎 URL
$baseUrl = $parts['scheme'] . '://' . $parts['host'] . (isset($parts['port']) ? ':' . $parts['port'] : '');
// 解析查詢字串為陣列
parse_str($parts['query'], $queryParams);
// $queryParams = ['name' => 'value', 'foo' => 'bar']
將 `application/x-www-form-urlencoded` 格式字串解析為陣列,支援巢狀陣列語法。
<?php
$str = 'user[name]=John&user[age]=30&tags[]=php&tags[]=laravel&tags[]=api';
parse_str($str, $arr);
/*
$arr = [
'user' => ['name' => 'John', 'age' => '30'],
'tags' => ['php', 'laravel', 'api'],
]
*/
// 注意:不指定第二參數會污染當前符號表(已棄用/移除)
// parse_str($str); // 錯誤!會建立 $user、$tags 變數
專注於檔案路徑分解:dirname、basename、extension、filename。
<?php
$path = '/var/www/html/api/v1/users/profile.php';
$info = pathinfo($path);
/*
Array
(
[dirname] => /var/www/html/api/v1/users
[basename] => profile.php
[extension] => php
[filename] => profile
)
*/
// 取得副檔名(單一用途更簡潔)
$ext = pathinfo($path, PATHINFO_EXTENSION); // 'php'
$filename = pathinfo($path, PATHINFO_FILENAME); // 'profile'
<?php
$params = [
'q' => 'php tutorial',
'page' => 1,
'tags' => ['php', 'laravel', 'api'],
'filters' => ['status' => 'published', 'author' => 123],
];
$query = http_build_query($params);
// q=php+tutorial&page=1&tags%5B0%5D=php&tags%5B1%5D=laravel&tags%5B2%5D=api&filters%5Bstatus%5D=published&filters%5Bauthor%5D=123
// 自定義分隔符(如 & for XML/HTML)
$query = http_build_query($params, '', '&');
<?php
function modifyUrlQuery(string $url, array $add = [], array $remove = []): string {
$parts = parse_url($url);
parse_str($parts['query'] ?? '', $query);
// 移除
foreach ($remove as $key) {
unset($query[$key]);
}
// 新增/更新
$query = array_merge($query, $add);
// 重建 URL
$newQuery = http_build_query($query);
$newUrl = $parts['scheme'] . '://' . $parts['host']
. (isset($parts['port']) ? ':' . $parts['port'] : '')
. $parts['path'];
if ($newQuery) $newUrl .= '?' . $newQuery;
if (isset($parts['fragment'])) $newUrl .= '#' . $parts['fragment'];
return $newUrl;
}
$url = 'https://example.com/search?q=php&page=1&sort=desc';
$newUrl = modifyUrlQuery($url, ['page' => 2, 'lang' => 'en'], ['sort']);
// https://example.com/search?q=php&page=2&lang=en
<?php
// 簡易路由匹配:/user/123/profile → ['id' => 123]
function matchRoute(string $pattern, string $uri): ?array {
// 將 {param} 轉為命名捕獲組
$regex = '#^' . preg_replace('/\{(\w+)\}/', '(?P<$1>[^/]+)', $pattern) . '$#';
if (preg_match($regex, $uri, $matches)) {
return array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
}
return null;
}
$route = '/user/{id}/post/{postId}';
$uri = '/user/456/post/789';
$params = matchRoute($route, $uri);
// ['id' => '456', 'postId' => '789']
<?php
// 白名單過濾:只保留允許的參數
function filterInput(array $input, array $allowedKeys): array {
return array_intersect_key($input, array_flip($allowedKeys));
}
$allowed = ['page', 'limit', 'sort', 'order'];
$cleanParams = filterInput($_GET, $allowed);
// 型別轉換與驗證
$page = (int) ($cleanParams['page'] ?? 1);
$limit = min(max((int) ($cleanParams['limit'] ?? 20), 1), 100); // 1-100
$sort = in_array($cleanParams['sort'] ?? 'id', ['id', 'name', 'created']) ? $cleanParams['sort'] : 'id';
$order = strtoupper($cleanParams['order'] ?? 'ASC') === 'DESC' ? 'DESC' : 'ASC';
<?php
$url = 'https://example.com/path?a=1&b=2&c=3&d=4&e=5#fragment';
$iterations = 100000;
$methods = [
'parse_url+parse_str' => fn() => { parse_str(parse_url($url, PHP_URL_QUERY), $q); return $q; },
'parse_url(PHP_URL_QUERY)' => fn() => parse_url($url, PHP_URL_QUERY),
'regex' => fn() => preg_match('/\?([^#]*)/', $url, $m) ? $m[1] : '',
];
foreach ($methods as $name => $fn) {
$start = hrtime(true);
for ($i = 0; $i < $iterations; $i++) $fn();
echo "$name: " . (hrtime(true) - $start) / 1e6 . " ms\n";
}
// 典型結果:
// parse_url+parse_str: 45.2 ms
// parse_url(PHP_URL_QUERY): 18.7 ms
// regex: 32.1 ms