Created
May 9, 2018 18:16
-
-
Save robocoder/33afa327be2838e83b13d6ddbc996c29 to your computer and use it in GitHub Desktop.
PHP build_url (opposite of parse_url)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 yup; I wish I made a note of where I copy/pasted this from ...
@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
The fragment should come after the query.