What is the recommended alternative to ECB mode for AES encryption in PHP?

The recommended alternative to ECB mode for AES encryption in PHP is CBC (Cipher Block Chaining) mode. CBC mode is more secure than ECB as it XORs each plaintext block with the previous ciphertext block before encryption. This helps prevent patterns in the plaintext from being visible in the ciphertext.

// Initialize the encryption key and initialization vector (IV)
$key = 'your_secret_key';
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));

// Encrypt the data using CBC mode
$encrypted_data = openssl_encrypt($data, 'aes-256-cbc', $key, 0, $iv);

// Decrypt the data using CBC mode
$decrypted_data = openssl_decrypt($encrypted_data, 'aes-256-cbc', $key, 0, $iv);