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;
}
@maikelvanmaurik
Copy link

The fragment should come after the query.

@robocoder
Copy link
Author

@maikelvanmaurik yup; I wish I made a note of where I copy/pasted this from ...

@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