Hello Magento Friends,
Today I bring you the solution for How to Encode and Decode URL in Magento 2.
Encryption is used to share confidential information. The plain text is converted into an encoded text that no one can understand. The encrypted text is then converted back into plain text. This process is known as decryption.
If you want to pass product ID or user ID into the URL, you can use encode URL for security purposes. Let’s learn How to Encode and Decode URL in Magento 2.
Steps to Encode and Decode URL in Magento 2:
Step 1: You need to insert \Magento\Framework\Url\EncoderInterface class to encode the URL and \Magento\Framework\Url\DecoderInterface class to decode the URL. Both classes must be inserted in your construct. I added this code in the custom module’s block file.
<?php namespace Vendor\Extension\Block; use Magento\Framework\Url\EncoderInterface; use Magento\Framework\Url\DecoderInterface; class CustomBlock extends \Magento\Framework\View\Element\Template { /** * @var EncoderInterface */ protected $url_Encode; /** * @var DecoderInterface */ protected $url_Decode; /** * @param EncoderInterface $url_Encode * @param DecoderInterface $url_Decode */ public function __construct( EncoderInterface $url_Encode, DecoderInterface $url_Decode) { $this->urlEncode = $url_Encode; $this->urlDecode = $url_Decode; } public function getEncodeUrl($url) { /** * $url = baseurl/mymodule/index * Output : pLzEyNy4wLjAuMS9tMjM0L2hlbGxvd29, */ return $this->urlEncode->encode($url); } public function getDecodeUrl($url) { /** * $url :pLzEyNy4wLjAuMS9tMjM0L2hlbGxvd29, * Output = baseurl/mymodule/index */ return $this->urlDecode->decode($url); } }
You need to pass a URL as a parameter in getEncodeUrl() and getDecodeUrl() to return output.
Output :
Base URL : baseurl/mymodule/index
Encode URL : pLzEyNy4wLjAuMS9tMjM0L2hlbGxvd29
Decode URL : baseurl/mymodule/index
Conclusion:
Hence, this way you can Encode and Decode URL in Magento 2. You can also Pass Parameter To URL In Magento 2. Share the article with your friends and stay in touch with us for upcoming Magento solutions.
Happy Coding!