How can PHP developers securely handle file encryption and decryption processes to prevent unauthorized access to sensitive data?

To securely handle file encryption and decryption in PHP, developers should use strong encryption algorithms like AES, securely store encryption keys, and properly handle key management. It's important to restrict access to the encryption keys and ensure that only authorized users can decrypt the data.

// Encrypt data using AES encryption
function encryptData($data, $key) {
    $cipher = "aes-256-cbc";
    $ivlen = openssl_cipher_iv_length($cipher);
    $iv = openssl_random_pseudo_bytes($ivlen);
    $encrypted = openssl_encrypt($data, $cipher, $key, 0, $iv);
    return base64_encode($iv . $encrypted);
}

// Decrypt data using AES decryption
function decryptData($data, $key) {
    $cipher = "aes-256-cbc";
    $data = base64_decode($data);
    $ivlen = openssl_cipher_iv_length($cipher);
    $iv = substr($data, 0, $ivlen);
    $encrypted = substr($data, $ivlen);
    return openssl_decrypt($encrypted, $cipher, $key, 0, $iv);
}

// Example usage
$key = "supersecretkey";
$data = "Sensitive data to encrypt";
$encryptedData = encryptData($data, $key);
echo "Encrypted data: " . $encryptedData . "\n";
$decryptedData = decryptData($encryptedData, $key);
echo "Decrypted data: " . $decryptedData;