Created
June 6, 2017 18:07
-
-
Save kamermans/0969fa03c6b1131db529410e4cf3b812 to your computer and use it in GitHub Desktop.
PHP function to cleanup/re-encode a 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
<?php | |
$url = 'http://foo.com/path with spaces/index.php?something=something else#foo-29 32'; | |
$reencode_url = function ($url) { | |
$url_parts = parse_url($url); | |
// Add scheme | |
$scheme = array_key_exists('scheme', $url_parts)? $url_parts['scheme']: 'http'; | |
$new_url = "$scheme://"; | |
// Add authentication | |
if (array_key_exists('user', $url_parts) && array_key_exists('pass', $url_parts)) { | |
$new_url .= rawurlencode($url_parts['user']).":".rawurlencode($url_parts['pass']).'@'; | |
} | |
// Add host | |
$new_url .= $url_parts['host']; | |
if (array_key_exists('port', $url_parts)) { | |
$new_url .= ':'.$url_parts['port']; | |
} | |
// Add path | |
$path = array_key_exists('path', $url_parts)? $url_parts['path']: '/'; | |
$path = implode('/', array_map('rawurlencode', explode('/', $path))); | |
$new_url .= $path; | |
// Add query string | |
if (array_key_exists('query', $url_parts)) { | |
$query = ''; | |
parse_str($url_parts['query'], $query); | |
$new_url .= '?'.http_build_query($query); | |
} | |
// Add fragment | |
if (array_key_exists('fragment', $url_parts)) { | |
$new_url .= '#'.rawurlencode($url_parts['fragment']); | |
} | |
return $new_url; | |
} | |
echo $reencode_url($url); | |
// http://foo.com/path%20with%20spaces/index.php?something=something+else#foo-29%2032 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment