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.
There are two ways in PHP to perform URL encoding and decoding. These are,
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://phppot.com/home.php?name=all about php"; $encodedUrl = urlencode($url); //returns http%3A%2F%2Fphppot.com%2Fhome.php%3Fname%3Dall+about+php echo $encodedUrl; //returns http://phppot.com/home.php?name=all about php echo urldecode($encodedUrl);
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://phppot.com/home.php?name=all about php"; $encodedUrl = rawurlencode($url); //returns http%3A%2F%2Fphppot.com%2Fhome.php%3Fname%3Dall%20about%20php echo $encodedUrl; //returns http://phppot.com/home.php?name=all about php echo rawurldecode($encodedUrl);
This PHP code tutorial was published on May 7, 2013.