[yii2] How to easily encrypt / decrypt URL parameters

If you want to encrypt URL parameters like this:

https://frontend.bardimin/country/view?id=1

Become like this:

https://frontend.bardimin/country/view?MN13pDvH/4+94LNY/NXJiDM4YTMwZjc5ZjRmMzA0Y2RjMDRmMjUyYmI5M2Q4MmE2ZDE4ODNkOTdkNzc1MGI3Yzg5OTE4NzVlMzBlMjZmNzkXVSsTf7d1y5a26LK8IcsggrWQi+hW4b0xIFKnIZowSTXZVxu+t2lGyx/skNKFo6g=

You can do it easily in yii2. Here are the steps to encrypt/decrypt on URL parameters such as the example above:

1. Create a UrlRule class

The first step you should do is to create a UrlRule file.php in the“common/helpers”directory if using yii2 advanced or directory“helpers” if using yii2 basic. Then copy/paste the following code:

<?php

namespace commonhelpers;

use yii;

class UrlRule implements yiiwebUrlRuleInterface
{

    public  $jklKey = '-YD07LTTJdSVB6oThcC7l60KeZTUXcNA'; //change if necessary

    public function createUrl($manager, $route, $params)
    {
        if ($params!==null) {
            $paramString = serialize($params);
            $paramStringEncoded = $paramString ? base64_encode(Yii::$app->security->encryptByKey($paramString,$this->jklKey,null)) : '';
        }
        return empty ($params)? $route: $route. '?' . $paramStringEncoded;
    }

public function parseRequest($manager, $request)
    {
        $pathInfo = $request->getPathInfo();
        $queryString=$request->getQueryString();
        if(!empty($queryString)) {
            $params=unserialize(Yii::$app->security->decryptByKey(base64_decode($queryString),$this->jklKey,null));
            foreach ($params as $key => $value) {
                $paramsQuery = [$key] $value;
            }
            [$pathInfo,$paramsQuery]return;
        }
        return false;
    }

}

2. Change the config/main file.php

Next change your config/play.php file like this:

    .............
	.............
	
'components' = > [
		.............
		.............
		.............

'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'enableStrictParsing' => false,
            'rules' = > [
                ['class' => 'commonhelpersUrlRule'],
            ],
        ],
		.............
		.............
	]
	.............
	.............
TOP TUTORIALS:  [Yii2] How to create and use Functions on Yii2 Basic and Advanced Templates

Leave a Comment

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