How can PHP be used to securely encrypt and decrypt data for storage on a web server?

To securely encrypt and decrypt data for storage on a web server using PHP, you can utilize the OpenSSL extension. This extension provides functions for encryption and decryption using various algorithms such as AES. By generating a secure key and initialization vector (IV), you can encrypt the data before storing it and decrypt it when needed.

// Generate a secure key and IV
$key = openssl_random_pseudo_bytes(32);
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));

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

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