PECLのhttp_build_urlとの互換性はありません。
関数定義
function build_url(array $elements) {
$e = $elements;
return
(isset($e['host']) ? (
(isset($e['scheme']) ? "$e[scheme]://" : '//') .
(isset($e['user']) ? $e['user'] . (isset($e['pass']) ? ":$e[pass]" : '') . '@' : '') .
$e['host'] .
(isset($e['port']) ? ":$e[port]" : '')
) : '') .
(isset($e['path']) ? $e['path'] : '/') .
(isset($e['query']) ? '?' . (is_array($e['query']) ? http_build_query($e['query'], '', '&') : $e['query']) : '') .
(isset($e['fragment']) ? "#$e[fragment]" : '')
;
}
例 (コード)
<?php
$patterns = [
['host' => 'example.com'],
['scheme' => 'https', 'host' => 'example.com'],
['scheme' => 'http', 'host' => 'example.com', 'port' => 8080, 'path' => '/x/y/z'],
['scheme' => 'http', 'host' => 'example.com', 'port' => 8080, 'user' => 'anonymous', 'query' => 'a=b&c=d', 'fragment' => 'xyz'],
['scheme' => 'http', 'host' => 'example.com', 'user' => 'root', 'pass' => 'stupid', 'path' => '/x/y/z', 'query' => ['a' => 'b', 'c' => 'd']],
['path' => '/x/y/z', 'query' => 'a=b&c=d'],
];
foreach ($patterns as $pattern) {
echo json_encode($pattern, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n/* " . build_url($pattern) . " */\n\n";
}
例 (結果)
{
"host": "example.com"
}
/* //example.com/ */
{
"scheme": "https",
"host": "example.com"
}
/* https://example.com/ */
{
"scheme": "http",
"host": "example.com",
"port": 8080,
"path": "/x/y/z"
}
/* http://example.com:8080/x/y/z */
{
"scheme": "http",
"host": "example.com",
"port": 8080,
"user": "anonymous",
"query": "a=b&c=d",
"fragment": "xyz"
}
/* http://anonymous@example.com:8080/?a=b&c=d#xyz */
{
"scheme": "http",
"host": "example.com",
"user": "root",
"pass": "stupid",
"path": "/x/y/z",
"query": {
"a": "b",
"c": "d"
}
}
/* http://root:stupid@example.com/x/y/z?a=b&c=d */
{
"path": "/x/y/z",
"query": "a=b&c=d"
}
/* /x/y/z?a=b&c=d */