Skip to content

Instantly share code, notes, and snippets.

@kamermans
Created June 6, 2017 18:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamermans/0969fa03c6b1131db529410e4cf3b812 to your computer and use it in GitHub Desktop.
Save kamermans/0969fa03c6b1131db529410e4cf3b812 to your computer and use it in GitHub Desktop.
PHP function to cleanup/re-encode a URL
<?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