Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save robocoder/33afa327be2838e83b13d6ddbc996c29 to your computer and use it in GitHub Desktop.
Save robocoder/33afa327be2838e83b13d6ddbc996c29 to your computer and use it in GitHub Desktop.
PHP build_url (opposite of parse_url)
/**
* Generate URL from its components (i.e., opposite of built-in php function, parse_url())
*
* @param array $components
*
* @return string
*/
function build_url($components)
{
$url = $components['scheme'] . '://';
if ( ! empty($components['username']) && ! empty($components['password'])) {
$url .= $components['username'] . ':' . $components['password'] . '@';
}
$url .= $components['host'];
if ( ! empty($components['port']) &&
(($components['scheme'] === 'http' && $components['port'] !== 80) ||
($components['scheme'] === 'https' && $components['port'] !== 443))
) {
$url .= ':' . $components['port'];
}
if ( ! empty($components['path'])) {
$url .= $components['path'];
}
if ( ! empty($components['fragment'])) {
$url .= '#' . $components['fragment'];
}
if ( ! empty($components['query'])) {
$url .= '?' . http_build_query($components['query']);
}
return $url;
}
@ceilidhboy
Copy link

@robocoder so correct it then! You can edit your gists :))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment