CakePHP3 with Hashids

Security by obscurity is never a good policy but there are still some legitimate reasons why you would want to hide your id’s. One good reason is that you don’t want to reveal how many users you perhaps have or at what rate your membership is growing. Making it difficult for the average website visitor to cycle through your id’s by just changing the URL is also important.

The following code should be used with other security measures that check that a user is authenticated and authorized to access a particular record or group of records. The implementation of such security is outside the scope of this article. Reading the CakePHP3 manual should provide you with enough detail on how to achieve this or alternative you should read my previous blog post on using CakePHP3 with TinyAuth.

Install the Hashids Library

The following is all based around using the excellent Hashids.org library. The library has been ported to a huge number of languages. You should visit the website and read the docs for more specific information.

All CakePHP3 users should be familiar with composer, so using the following method to install Hashids is prefered.

Update AppController

Add the following code to your AppController

Notice you can set a couple of parameters. First you need to create your own “salt” just vist random.org and generate a string of characters. You can also change the “min_hash_length” and change the “alphabet” characters that are used for string generation.

Using Hashids in Controllers

Encoding and decoding id integers is now super easy.

Typically I use the decode function inside of controllers as the id string will already be encoded inside the view template and passed back to the controller.

Using Hashids in Template Views

First we need to pass an instance of hashids() to the view. We do that with $this->set().

The important bit is this.

Then inside of views we can access the hashids() object.

You can also use this inside loops to encode or decode lists of id’s and so forth. Let me know if it helped you out or you think the code can be improved.

That’s really all there is to it!

Since writing this article a better cleaner solution is available from the UseMuffin Team. I recommend the UseMuffin/Obfuscate CakePHP 3 Plugin: https://github.com/UseMuffin/Obfuscate

This plugin supports a variety of external obfuscation libraries and the behavior can be configured on a per Model basis.

Tags: , , ,

No comments yet.

Leave a Reply