PHP: percent-encoding aka URL encoding

Percent-encoding, also known as URL encoding, is a mechanism for encoding information in a Uniform Resource Identifier (URI) under certain circumstances. In PHP you have rawurlencode, rawurldecode for “raw” URL encoding as well as the urlencode and urldecode for the slightly different encoding that is used in the query (rather known as application/x-www-form-urlencoded where the space is encoded with + instead of %20):

  • rawurlencode follows RFC 1738 prior to PHP 5.3.0 and RFC 3986 afterwards
  • urlencode encodes spaces as plus signs (not as %20 as done in rawurlencode)

One practical reason to choose one over the other is if you’re going to use the result in another environment, for example JavaScript.
In PHP urlencode(‘test 1’) returns ‘test+1’ while rawurlencode(‘test 1’) returns ‘test%201’ as result. But if you need to decode this in JavaScript using decodeURI() function then decodeURI(“test+1”) will give you “test+1” while decodeURI(“test%201”) will give you “test 1” as result. In such cases the rawurlencode PHP function should be used.