Build a URL from parse_url parts. The generated URL will be a relative URL if a scheme or host are not provided.
array $parts Array of parse_url parts:
string
public static function buildUrl(array $parts) {
$url = $scheme = '';
if (isset($parts['scheme'])) {
$scheme = $parts['scheme'];
$url .= $scheme . '://';
}
if (isset($parts['host'])) {
if (isset($parts['user'])) {
$url .= $parts['user'];
if (isset($parts['pass'])) {
$url .= ':' . $parts['pass'];
}
$url .= '@';
}
$url .= $parts['host'];
// Only include the port if it is not the default port of the scheme
if (isset($parts['port']) && !($scheme == 'http' && $parts['port'] == 80 || $scheme == 'https' && $parts['port'] == 443)) {
$url .= ':' . $parts['port'];
}
}
if (empty($parts['path'])) {
$url .= '/';
}
else {
if ($parts['path'][0] != '/') {
$url .= '/';
}
$url .= $parts['path'];
}
// Add the query string if present
if (!empty($parts['query'])) {
if ($parts['query'][0] != '?') {
$url .= array_key_exists('query_prefix', $parts) ? $parts['query_prefix'] : '?';
}
$url .= $parts['query'];
}
// Ensure that # is only added to the url if fragment contains anything.
if (isset($parts['fragment']) && !empty($parts['fragment'])) {
$url .= '#' . $parts['fragment'];
}
return $url;
}