PHP URL Encoding Decoding

May 7, 2013

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 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 address bar that will prevent further navigation to the right page as expected.

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

Other 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);



Comments on
PHP URL Encoding Decoding
  • Gideon Birimuye

    Hi Vincy, Ive been farming on your blog and i have found it interesting (php wise). A week back i started programming in php and I’m having fun with it. Now that i have found you i believe you can be a handy tutor as regards helping me understand this language. I’m looking forward to sharing more with you.

Add a Comment