URL encoding and decoding using php

php url encode and decode
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. They 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 = "http://sillyhelp.com/home.php?name=all about php";
$encodedUrl = urlencode($url);

echo $encodedUrl; //returns http%3A%2F%2Fsillyhelp.com.com%2Fhome.php%3Fname%3Dall+about+php

echo urldecode($encodedUrl); //returns http://sillyhelp.com/home.php?name=all about php

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 = "http://sillyhelp.com/home.php?name=all about php";
$encodedUrl = rawurlencode($url);

echo $encodedUrl; //returns http%3A%2F%2Fsillyhelp.com%2Fhome.php%3Fname%3Dall%20about%20php

echo rawurldecode($encodedUrl); //returns http://sillyhelp.com/home.php?name=all about php

You may also like...