How to Encode and Decode URL in Magento 2?

In today's tutorial, we will bring to you a step by step guide on how to encode and decode URL in Magento 2. To ensure the security of your ecommerce websites, it is required to set the encode URL and to get value, it is required to decode the URL.

Here, we will guide you on how to encode and decode the URL using the Magento default function.

Let's begin with the steps to encode and decode URL in Magento 2.

First of all, we assume that you already have a simple module.

Post that, it is required to inject \Magento\Framework\Url\EncoderInterface to encode URL and \Magento\Framework\Url\DecoderInterface to decode the URL in the construct.

<?php

namespace MageDelight\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)
    {
      
        return $this->urlEncode->encode($url);
    }

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

This code can be used in any file. All you need to do is pass URL as parameter in getEncodeUrl() and getDecodeUrl() to return output.

Output :

  • Base URL:http://125.0.1.1/md1005/helloworld
  • Encode URL: aHR0cDovLzEyNy4wLjAuMS9tMjM0L2hlbGxvd29ybGQ
  • Decode URL:http://125.0.1.1/md1005/helloworld

Also read: How to Fetch getUrl() in Plugin or Observer file in Magento 2?

We hope we've covered every step in this article about how to encode and decode URL in Magento 2. If we missed out on anything, feel free to reach us out.