What are the best practices for generating and handling the Initialization Vector in mycrypt encryption in PHP?

When using mycrypt encryption in PHP, it is important to generate a secure Initialization Vector (IV) for each encryption operation to ensure the security of the encrypted data. The IV should be unique for each encryption and should be included with the encrypted data for decryption. It is recommended to use a secure random number generator to generate the IV.

// Generate a secure Initialization Vector (IV)
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));

// Encrypt data with IV
$ciphertext = openssl_encrypt($data, 'aes-256-cbc', $key, 0, $iv);

// Store IV with encrypted data
$encryptedData = $iv . $ciphertext;

// Decrypt data with IV
$iv = substr($encryptedData, 0, openssl_cipher_iv_length('aes-256-cbc'));
$ciphertext = substr($encryptedData, openssl_cipher_iv_length('aes-256-cbc'));
$decryptedData = openssl_decrypt($ciphertext, 'aes-256-cbc', $key, 0, $iv);