in my ZF2 application I want to encrypt my parameters, so that when having a link like /product/update/1 will be displayed as /product/update/cdsk45kdi340kd0wlw0 or something similar. I need to encrypt and decrypt it in controllers and views. What is the best approach to this? Thank you for any help.
Asked
Active
Viewed 537 times
0
-
Can you explain the reason to use "encryption" for this? Why is a uuid, slug or a hash not sufficient? – Jurian Sluiman Mar 12 '14 at 10:44
-
I just want to avoid that a user may call an url with guessing the id's... Hash would be a good alternative, can you give me an example? – cwhisperer Mar 12 '14 at 10:55
2 Answers
1
make route look like this
'product' => array(
'type' => 'Zend\Mvc\Router\Http\Segment',
'options' => array(
'route' => '/product/update[/:hashedid]',
'constraints' => array(
'hashedid' => '[a-zA-Z0-9-_\.]+',
),
'defaults' => array(
'controller' => 'Index',
'action' => 'index',
),
),
),
and in controller
$hashedid = $this->params()->fromRoute('hashedid', 0);
$id = $this->dehash($hashedid);

Skaza
- 466
- 4
- 13
-
thank you for the reply... but what do I use for hashing the id? I would prefer using a salt for hashing... – cwhisperer Mar 12 '14 at 12:21
-
@cwhisperer you can use whatever you want salt sound good here http://stackoverflow.com/a/1289114/3223896 – Skaza Mar 12 '14 at 12:58
-
thank you for the link. Unfortunately the base64_encode generates slashes(/) in the encrypted string, which makes my route, checked agains the constraint, invalid .... – cwhisperer Mar 13 '14 at 15:56
1
The point here is that you want to avoid users to guess the url. I would generate a random token per product. Store in your database this token together with the id of the product (and all other properties).
To generate a random string as a token, you can use Zend\Math\Rand
: Rand::getString(10);
gives you a random string of 10 characters. When you store the products in your database, generate a random string for every product. Then, in your controller you do not get the product based on the identifier (id), but based on the token.

Jurian Sluiman
- 13,498
- 3
- 67
- 99
-
1Make sure you validate for uniqueness. You could also use uniqid() instead of a random function. – dualmon Mar 12 '14 at 15:08
-
Sure, good point. Set a unique constraint on your database at least and check if the token already exists. – Jurian Sluiman Mar 12 '14 at 15:40
-
1Rather than generate random, you could base64 or md5 the id and name together, it would save you storing anything on the DB (another DB call to retrieve). This is how external unique URLs are usually handled. If it needs to be unique per user, you can include the users email and/or ID in the string you encrypt/encode. – lukeocodes Mar 12 '14 at 17:28