What best practices should be followed when encrypting sensitive data in PHP applications?

When encrypting sensitive data in PHP applications, it is important to use strong encryption algorithms such as AES with a secure key length. Additionally, always store encryption keys securely and never hardcode them in your code. It's also recommended to use a secure method for key management, such as a key management service.

// Generate a secure encryption key
$key = random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES);

// Encrypt the sensitive data using AES encryption
$encryptedData = sodium_crypto_secretbox($data, $nonce, $key);

// Decrypt the sensitive data
$decryptedData = sodium_crypto_secretbox_open($encryptedData, $nonce, $key);