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?
@deceze definitely got me going down the right path, so go upvote his answer. But here is exactly what worked:
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 needrawurlencode()for the path so that spaces get encoded as%20and 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.