Back to Fred Mac Donald's Blog

php urlencode() or rawurlencode()

php urlencode() or rawurlencode()

Short discussion about the difference between the two php functions.

After struggling with an image that does not get scraped in Facebook Debugger because the user named the image name with a space in it instead of using only alphanumeric characters in the filename and using urlencode() instead of rawurlencode() to fix the problem I decided to document the difference once and for all.

What does the php manual say?

urlencode()

Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type.

This means that a filename like “file name.jpg” is encoded as “file+name.jpg
Obviously, file+name.jpg does not exist and the server was trying hard to fulfil the request but eventually gave up with an HTTP 400 error

rawurlencode()

Returns a string in which all non-alphanumeric characters except -_.~ have been replaced with a percent (%) sign followed by two hex digits. This is the encoding described in » RFC 3986 for protecting literal characters from being interpreted as special URL delimiters, and for protecting URLs from being mangled by transmission media with character conversions (like some email systems).

This means that a filename like “file name.jpg” is encoded as “file%20name.jpg
The server will understand what to do if this filename is requested and server the correct image.

Written by:  - 31 Aug, 2018  
comments powered by Disqus
flashy