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. You may also like How to check validation url www and href in PHP and How to PHP Validate URL.

HTML Code

<html>
    <body>
        <?=$converted_url?>
        <form method="post" action="">
            <input type="text" name="url" placeholder="Enter URL To Encode">
            <input type="submit" name="encode_url" value="ENCODE">
        </form>
        <form method="post" action="">
            <input type="text" name="url" placeholder="Enter URL To Decode">
            <input type="submit" name="decode_url" value="DECODE">
        </form>
    </body>
</html>

PHP Code

<?php
$converted_url = '';
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;
}
?>

Leave a Reply

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