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
routeTo_myOtherControllerAction:
path: /item/show/{id}
defaults: { _controller: appBundle:Items:show }
options:
crypt_auto: true
crypt_method: %default_crypt_method%
I couldn't find any other solution than my service yet. Any ideas?
Thanks in advance!
So, just to clarify:
If you answered "yes" to both questions, consider following this guide to URL parameter encryption.
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:
routing.yml
my-path-in-the-routing:
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);
//....
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With