-
Notifications
You must be signed in to change notification settings - Fork 2
Open
Labels
Description
This discussion in stackoverflow explicits the problem in detail.
https://stackoverflow.com/questions/4354904/php-parse-url-reverse-parsed-url
The best solution seems, to me, to be https://stackoverflow.com/a/31691249/2714285 as it provides tests:
function unparse_url(array $parsed): string {
$pass = $parsed['pass'] ?? null;
$user = $parsed['user'] ?? null;
$userinfo = $pass !== null ? "$user:$pass" : $user;
$port = $parsed['port'] ?? 0;
$scheme = $parsed['scheme'] ?? "";
$query = $parsed['query'] ?? "";
$fragment = $parsed['fragment'] ?? "";
$authority = (
($userinfo !== null ? "$userinfo@" : "") .
($parsed['host'] ?? "") .
($port ? ":$port" : "")
);
return (
(\strlen($scheme) > 0 ? "$scheme:" : "") .
(\strlen($authority) > 0 ? "//$authority" : "") .
($parsed['path'] ?? "") .
(\strlen($query) > 0 ? "?$query" : "") .
(\strlen($fragment) > 0 ? "#$fragment" : "")
);
}function unparse_url_test() {
foreach ([
'',
'foo',
'http://www.google.com/',
'http://u:p@foo:1/path/path?q#frag',
'http://u:p@foo:1/path/path?#',
'ssh://root@host',
'://:@:1/?#',
'http://:@foo:1/path/path?#',
'http://@foo:1/path/path?#',
] as $url) {
$parsed1 = parse_url($url);
$parsed2 = parse_url(unparse_url($parsed1));
if ($parsed1 !== $parsed2) {
print var_export($parsed1, true) . "\n!==\n" . var_export($parsed2, true) . "\n\n";
}
}
}
unparse_url_test();