To pass an encrypted value in a URL and decrypt it in CodeIgniter 4 (CI4), you can use the Encryption
library provided by CI4. Here’s how to implement this:
1. Configure Encryption in CI4
Ensure that the encryption service is properly set up. Open the app/Config/Encryption.php
file and configure it:
1 2 3 4 5 6 7 8 9 10 11 | <?php namespace Config; use CodeIgniter\Config\BaseConfig; class Encryption extends BaseConfig { public $key = 'your-encryption-key'; // Replace with a random key public $driver = 'OpenSSL'; // Use OpenSSL for encryption } |
Replace your-encryption-key
with a strong random key. You can generate one using bin2hex(random_bytes(32))
in PHP.
2. Encrypt the Value
Use CI4’s encrypter()
helper to encrypt the value before adding it to the URL:
1 2 3 4 5 6 7 8 9 10 11 12 | use CodeIgniter\Encryption\Encryption; $encrypter = \Config\Services::encrypter(); // The value to encrypt $data = 'your-value-to-encrypt'; // Encrypt the value $encryptedValue = base64_encode($encrypter->encrypt($data)); // Pass the encrypted value in the URL $url = base_url('your-controller/your-method/' . $encryptedValue); |
3. Decrypt the Value
Retrieve and decrypt the value in your controller:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public function yourMethod($encryptedValue) { $encrypter = \Config\Services::encrypter(); // Decode and decrypt the value try { $decryptedValue = $encrypter->decrypt(base64_decode($encryptedValue)); echo 'Decrypted Value: ' . $decryptedValue; } catch (\Exception $e) { // Handle errors (e.g., invalid encryption or tampered data) echo 'Decryption failed: ' . $e->getMessage(); } } |
4. Example Flow
- Encrypt and Generate URL: