整理 PHP 處理 URL 的核心函數:建構查詢字串、解析 URL 結構、編碼/解碼,並說明 http_build_query 與 compact 搭配建構乾淨 URL 的技巧。
$data = [
'foo' => 'bar',
'baz' => 'boom',
'cow' => 'milk',
'php' => 'hypertext processor'
];
echo http_build_query($data);
// foo=bar&baz=boom&cow=milk&php=hypertext+processor
// 數值索引陣列加前綴
echo http_build_query(['apple', 'banana'], 'fruit_');
// fruit_0=apple&fruit_1=banana
$city = 'San Francisco';
$state = 'CA';
$event = 'SIGGRAPH';
$result = compact('city', 'state', 'event');
// ['city'=>'San Francisco', 'state'=>'CA', 'event'=>'SIGGRAPH']
// 實務:過濾空值再建構 URL
$qs = compact('province', 'city', 'name');
foreach ($qs as $k => $v) if (!$v) unset($qs[$k]);
$url = 'something/search/?' . http_build_query($qs);
$url = 'https://user:pass@example.com:8080/path?query=value#fragment';
print_r(parse_url($url));
/*
Array
(
[scheme] => https
[host] => example.com
[port] => 8080
[user] => user
[pass] => pass
[path] => /path
[query] => query=value
[fragment] => fragment
)
*/
| 函數 | 用途 | 空格處理 | 標準 |
|---|---|---|---|
urlencode() | 表單/查詢字串編碼 | + | application/x-www-form-urlencoded |
urldecode() | 對應解碼 | +→空格 | |
rawurlencode() | URL 路徑/片段編碼 | %20 | RFC 3986 |
rawurldecode() | 對應解碼 | 不處理 + |
// 產生 FTP 帶密碼連結
$link = 'ftp://user:' . rawurlencode('foo @+%/') . '@ftp.example.com/file.txt';
// ftp://user:foo%20%40%2B%25%2F@ftp.example.com/file.txt
// 解析並重組 URL
$parts = parse_url($url);
$newQuery = http_build_query(array_merge(
[], // 解析 query string: parse_str($parts['query'], $qs);
['new_param' => 'value']
));
$newUrl = $parts['scheme'] . '://' . $parts['host'] . $parts['path'] . '?' . $newQuery;