12

I need to URL encode just the directory path and file name of a URL using PHP.

So I want to encode something like http://example.com/file name and have it result in http://example.com/file%20name.

Of course, if I do urlencode('http://example.com/file name'); then I end up with http%3A%2F%2Fexample.com%2Ffile+name.

The obvious (to me, anyway) solution is to use parse_url() to split the URL into scheme, host, etc. and then just urlencode() the parts that need it like the path. Then, I would reassemble the URL using http_build_url().

Is there a more elegant solution than that? Or is that basically the way to go?

2
  • That seems like the most robust solution to me.
    – Herbert
    Nov 1, 2011 at 22:45
  • Per documentation: urlencode is for the query part of a URL. rawurlencode for the path, but make sure to exclude slashes. Dec 17, 2017 at 11:52

5 Answers 5

21

@deceze definitely got me going down the right path, so go upvote his answer. But here is exactly what worked:

    $encoded_url = preg_replace_callback('#://([^/]+)/([^?]+)#', function ($match) {
                return '://' . $match[1] . '/' . join('/', array_map('rawurlencode', explode('/', $match[2])));
            }, $unencoded_url);

There are a few things to note:

  • http_build_url requires a PECL install so if you are distributing your code to others (as I am in this case) you might want to avoid it and stick with reg exp parsing like I did here (stealing heavily from @deceze's answer--again, go upvote that thing).

  • urlencode() is not the way to go! You need rawurlencode() for the path so that spaces get encoded as %20 and not +. Encoding spaces as + is fine for query strings, but not so hot for paths.

  • This won't work for URLs that need a username/password encoded. For my use case, I don't think I care about those, so I'm not worried. But if your use case is different in that regard, you'll need to take care of that.

1
  • Right, I forgot to piece the complete URL back together again. I guess one could change the regex to do non-capturing look-behinds so it only extracts and modifies the path. +1 anyway. :)
    – deceze
    Nov 2, 2011 at 1:40
17

As you say, something along these lines should do it:

$parts = parse_url($url);
if (!empty($parts['path'])) {
    $parts['path'] = join('/', array_map('rawurlencode', explode('/', $parts['path'])));
}
$url = http_build_url($parts);

Or possibly:

$url = preg_replace_callback('#https?://.+/([^?]+)#', function ($match) {
           return join('/', array_map('rawurlencode', explode('/', $match[1])));
       }, $url);

(Regex not fully tested though)

2
  • +1 for realizing that the slashes in the path will mess everything up if they are not given special handling like you did.
    – Trott
    Nov 1, 2011 at 22:55
  • Nice. The regexp does need some tweaking, but it set me down the right path.
    – Trott
    Nov 1, 2011 at 23:40
1
function encode_uri($url){
    $exp = "{[^0-9a-z_.!~*'();,/?:@&=+$#%\[\]-]}i";
    return preg_replace_callback($exp, function($m){
        return sprintf('%%%02X',ord($m[0]));
    }, $url);
}
0

Much simpler:

$encoded = implode("/", array_map("rawurlencode", explode("/", $path)));
3
  • 2
    please explain your answer as it is an old question it is recommended you tell us how your answer is different than others already provided. Thank you. Jul 1, 2014 at 5:35
  • 1
    This answer is incorrect. It will encode the colon that follows the scheme. Given the input http://example.com/file name, it produces http%3A//example.com/file%20name. The correct result is http://example.com/file%20name.
    – Trott
    Jul 1, 2014 at 16:05
  • This works just fine if you are working with a path, as indicated by the $path variable in the sample code.
    – cjbarth
    Feb 11, 2019 at 16:28
-1

I think this function ok:

function newUrlEncode ($url) {
    return str_replace(array('%3A', '%2F'), '/', urlencode($url));
}
1
  • This works for the example in the question, but it is not robust. For example, it returns the wrong result if a port is specified in the URL.
    – Trott
    May 20, 2013 at 3:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.