PHP URL Encoding Decoding

Last modified on February 25th, 2017 by Vincy.

PHP supports encoding and decoding of URL by providing some built-in functions. Encoding is required before sending URL data to query string or to a function which might dynamically work on this URL data. And then, this data will be decoded into its original form, after receiving it in target PHP page or function.

Types of URL encoding and decoding in PHP

There are two ways in PHP to perform URL encoding and decoding. These are,

  1. application/x-www-form-urlencoded type
  2. RFC 3986 standard type

application/x-www-form-urlencoded type

This type of encoding and decoding is performed by the PHP built-in functions, urlencode() and urldecode(), respectively. We can prefer this type when we need to send the URL to the query string submitted from the form.

This functions will replace the special characters except (_), (-) and (.) that occurs in the given URL with %[hex code]; space will be replaced with ‘+’ character.

If we send URL without encoding, then the special characters if any, will truncate the actual page URL in the address bar that will prevent further navigation to the right page as expected.

The following example will show the effect of applying these functions in a PHP script.

$url = " about php";
$encodedUrl = urlencode($url);
echo $encodedUrl;
//returns about php
echo urldecode($encodedUrl);


RFC 3986 standard type

Another set of two PHP functions, rawurlencode() and rawurldecode() are used in this type of encoding and decoding. Unlike the previous type, the space that occurs in URL will be replaced with %[hext code].

This method differs from the previous method based on the RFC standard. And this type will be preferred, when we need to create URL dynamically.

Below sample code shows how to use both functions for URL encoding and decoding.

$url = " about php";
$encodedUrl = rawurlencode($url);
echo $encodedUrl;
//returns about php
echo rawurldecode($encodedUrl);

This PHP code tutorial was published on May 7, 2013.

↑ Back to Top

Share this Article