PHP urlencode And urldecode functions and it’s usage

By Faruque Ahamed Mollick

PHP has two inbuilt function urlencode() and urldecode() which can be used for encoding and be decoding a string. This two function can send a query and to get query through URL.



PHP urlencode() function

Urlencode in PHP can be used to encode a string that can be used in a URL. It simply returns the URL encoded version of the given string that is ready to use in URL. It encodes in the same way posted data from a web page is encoded and getting it with form GET method. It returns the encoded string after you use urlencode(). Here is the usage of this function:

urlencode (string $str )

Below is a simple example which displays an encoded string on the web page:

<?php
$str = "This text will be encode by PHP URL encode function";
$encoded_string = urlencode ($str );
echo $encoded_string;
?>

Now f you test it on the server then it will display the encoded string that is ready to use in URL. It will return you the encoded text that you can see below:

This+text+will+be+encode+by+PHP+URL+encode+function

 

PHP urldecode() function

urldecode() function of PHP decodes any URL encoded string. below is how to use urldecode() function in PHP:

urldecode (string $str )

Now suppose, we have a URL encoded string and we need to decode it so that it will be easy to read for normal users. Below is the simple example code snippet which is doing this task very well:

<?php
$str = "This+text+has+come+by+decoding+a+URL+encoded+string";
$decoded_string = urldecode ($str );
echo $decoded_string;
?>

If you test the above code, then it will return the below text which is decoded from the URL-encoded string:

This text has come by decoding a URL encoded string

So you have seen that it is so easy to encode and decode any string using urlencode() and urldecode() PHP function. I hope it is now clear to you and you have understood the example codes of this post.

Leave a Reply

Your email address will not be published. Required fields are marked *