Home » Php » php – Symfony: How to encrypt/decrypt route parameters automatically?

php – Symfony: How to encrypt/decrypt route parameters automatically?

Posted by: admin July 12, 2020 Leave a comment


I’d like to en-/decrypt parameters (e.g. IDs) in the URL/route automatically, example:

domain.com/item/show/1 should look like domain.com/item/show/uj7hs2.

Current (pseudo-)code

public function myControllerFunctionAction() {
    // ...
    $id = $this->get('my.crypt')->encrypt($item->getId());
    return $this->redirectToRoute('routeTo_myOtherControllerAction', array('id' => $id));

public function myOtherControllerFunctionAction($id) {
    $id = $this->get('my.crypt')->decrypt($id); // decrypt

    $item = $this->get('my.repository')->find($id);
    // ...

I’d like to avoid manually en-/decrypting.

Something like this would be perfect:

# routing.yml
    path:     /item/show/{id}
    defaults: { _controller: appBundle:Items:show }
        crypt_auto: true
        crypt_method: %default_crypt_method%

I couldn’t find any other solution than my service yet. Any ideas?

Thanks in advance!

How to&Answers:

So, just to clarify:

  1. You want to obfuscate the database record ID (i.e. primary key)?
  2. You want the resulting URL to be short.

If you answered “yes” to both questions, consider following this guide to URL parameter encryption.

What People Want To Do Here

Some encryption function is used to deterministically retrieve the ID

What People Should Do Instead

Use a separate column

What if I’m Okay with Longer URLs?

Use defuse/php-encryption. It provides authenticated encryption and is one of the most well studied PHP encryption libraries available. (It’s also permissively licensed.)

$decrypted = Crypto::decrypt($urlParameter, $yourKey);
// ... snip ... //
echo "<a href=\"/your/url/?".http_build_query([
    'id' => Crypto::encrypt($yourRowId, $yourKey)


You can do it with NzoUrlEncryptorBundle which is what I used for same reason. I’m just giving you examples below referencing to the its readme file. You can have a look at it for more details.

Features include:

  • Url Data & parameters Encryption
  • Url Data & parameters Decryption
  • Data Encryption & Decryption
  • Access from Twig by ease
  • Flexible configuration


    path: /my-url/{id}
    defaults: {_controller: MyBundle:MyController:MyFunction}

In the controller with annotation service

use Nzo\UrlEncryptorBundle\Annotations\ParamDecryptor;

     * @ParamDecryptor(params="id, toto, bar")
     public function indexAction(User $id, $toto) 
        // no need to use the decryption service here as the parameters are already decrypted by the annotation service.


In the controller without annotation service:

public function indexAction($id) 
    $MyId = $this->get('nzo_url_encryptor')->decrypt($id);



 public function indexAction() 

    $Encrypted = $this->get('nzo_url_encryptor')->encrypt($data);