DEV Community

Nilanchal
Nilanchal

Posted on • Originally published at stacktips.com on

How to Encode and Decode URL in 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.

PHP Encode and Decode URL Example :

First, let us create an HTML file and save it as sample.html

*sample.html *

<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>
Enter fullscreen mode Exit fullscreen mode

Let us now, 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;
   }
?>

Enter fullscreen mode Exit fullscreen mode

Lets see the simple example to encode and decode URL in PHP:

$url = "https://www.example.com/p/selenium.html";
//encoding URL
$encodedUrl = urlencode($url);
echo $encodedUrl;
//Prints: https%3A%2F%2Fwww.example.com%2Fp%2Fselenium.html

//decoding URL
echo urldecode($encodedUrl);
//Prints: https://www.example.com/p/selenium.html
Enter fullscreen mode Exit fullscreen mode

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

The post How to Encode and Decode URL in PHP first appeared on Stacktips.

Top comments (0)