Saturday, September 15, 2018

How to Encode and Decode URL Using PHP

This post explains how to encode and decode URL using php. 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.

How to Encode and Decode URL Using PHP

PHP Encode and Decode URL Example :

1. Create a HTML file and save it as sample.html

sample.html 
<html>
<body>
<div id="wrapper">

<div id="url_div">
 <form method="post" action="encode_decode.php">
 <input type="text" name="url" placeholder="Enter URL To Encode">
 <input type="submit" name="encode_url" value="ENCODE">
 </form>

 <form method="post" action="encode_decode.php">
 <input type="text" name="url" placeholder="Enter URL To Decode">
 <input type="submit" name="decode_url" value="DECODE">
 </form>
</div>

</div>
</body>
</html>

2. Create a PHP file to encode and decode url.

encode_decode.php
<?php
if(isset($_POST['encode_url']))
{
 $url = $_POST['url'];
 $encodedUrl = urlencode($url);
 $converted_url=$encodedUrl;
}

if(isset($_POST['decode_url']))
{
 $url = $_POST['url'];
 $decodedUrl = urldecode($url);
 $converted_url=$decodedUrl;
}
?>

Lets see the simple example to encode and decode URL in php :
$url = "https://www.skptricks.com/p/selenium.html";

//performing url encode using urlencode function
$encodedUrl = urlencode($url);
//returns https%3A%2F%2Fwww.skptricks.com%2Fp%2Fselenium.html
echo $encodedUrl;

//performing url decode using urldecodefunction
echo urldecode($encodedUrl);
//returns https://www.skptricks.com/p/selenium.html

This all about encoding and decoding URL in php. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.


No comments:

Post a Comment