All solutions proposed here are incorrect, because they do not avoid the query string part and the base directory part. In addition, they do not take into account the custom, missing, and fragmented parts of the URL.
To correctly display a valid URL, you need to separately remove the path part and the request part. So the solution is to extract the parts of the url, avoid each part and rebuild the URL.
Here is a simple piece of code:
function safeUrlEncode( $url ) { $urlParts = parse_url($url); $urlParts['path'] = safeUrlEncodePath( $urlParts['path'] ); $urlParts['query'] = safeUrlEncodeQuery( $urlParts['query'] ); return http_build_url($urlParts); } function safeUrlEncodePath( $path ) { if( strlen( $path ) == 0 || strpos($path, "/") === false ){ return ""; } $pathParts = explode( "/" , $path ); return implode( "/", $pathParts ); } function safeUrlEncodeQuery( $query ) { $queryParts = array(); parse_str($query, $queryParts); $queryParts = urlEncodeArrayElementsRecursively( $queryParts ); return http_build_query( $queryParts ); } function urlEncodeArrayElementsRecursively( $array ){ if( ! is_array( $array ) ) { return urlencode( $array ); } else { foreach( $array as $arrayKey => $arrayValue ){ $array[ $arrayKey ] = urlEncodeArrayElementsRecursively( $arrayValue ); } } return $array; }
Using will be simple:
$encodedUrl = safeUrlEncode( $originalUrl );
Side note In my code snippet, I use http://php.net/manual/it/function.http-build-url.php , which is available under the PECL extension. If you do not have a PECL extension on your server, you can simply enable a clean PHP implementation: http://fuelforthefire.ca/free/php/http_build_url/
Greetings :)
source share