Magento, Magento 2

How to Encode and Decode URL in Magento 2

How to Encode and Decode URL in Magento 2

In this tutorial, Today I will explain to how to encode and decode URL in Magento 2. For the security purpose, Sometimes we need to require to set encode URL and for get value we need to decode it. Using Magento default function we can encode and decode URL.

You may also like this :

Let’s follow the steps to Encode and Decode URL in Magento 2 :

First of all, Let’s assume that you have created simple module. After that, You need to inject  \Magento\Framework\Url\EncoderInterface for encode URL and \Magento\Framework\Url\DecoderInterface for decode URL these both class in your construct. I added this code in custom module’s block file.

<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Block;

use Magento\Framework\Url\EncoderInterface;
use Magento\Framework\Url\DecoderInterface;

class Helloworld extends \Magento\Framework\View\Element\Template {
    /**
     * @var EncoderInterface
     */
    protected $urlEncode;

    /**
     * @var DecoderInterface
     */
    protected $urlDecode;

    /**
     * @param EncoderInterface $urlEncode
     * @param DecoderInterface $urlDecode
     */
    public function __construct(
        EncoderInterface $urlEncode,
        DecoderInterface $urlDecode
    ) {
        $this->urlEncode = $urlEncode;
        $this->urlDecode = $urlDecode;
    }

    public function getEncodeUrl($url)
    {
        /**
         * $url =  http://127.0.0.1/m234/helloworld
         * Output : aHR0cDovLzEyNy4wLjAuMS9tMjM0L2hlbGxvd29ybGQ,
         */
        return $this->urlEncode->encode($url);
    }

    public function getDecodeUrl($url)
    {
        /**
         * $url : aHR0cDovLzEyNy4wLjAuMS9tMjM0L2hlbGxvd29ybGQ,
         * Output =  http://127.0.0.1/m234/helloworld
         */
        return $this->urlDecode->decode($url);
    }
}

You can use this code in any file. You need to pass URL as parameter in getEncodeUrl() and getDecodeUrl() to return output.

Output :

  • Base URL :  http://127.0.0.1/m234/helloworld
  • Encode URL : aHR0cDovLzEyNy4wLjAuMS9tMjM0L2hlbGxvd29ybGQ
  • Decode URL : http://127.0.0.1/m234/helloworld

I hope this blog is easy to understand about how to encode and decode URL in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Stay Safe and Stay Connected !!

 

Tagged ,