To encrypt and decrypt data in PHP, you can use the openssl_encrypt and openssl_decrypt functions. Here's a simple example:

<?php
function encryptData($data, $key, $iv) {
    $cipher = "aes-256-cbc";
    $options = 0;
    $encrypted = openssl_encrypt($data, $cipher, $key, $options, $iv);
    return $encrypted;
}

function decryptData($data, $key, $iv) {
    $cipher = "aes-256-cbc";
    $options = 0;
    $decrypted = openssl_decrypt($data, $cipher, $key, $options, $iv);
    return $decrypted;
}

// Example usage
$key = "your_secret_key";  // Replace with a strong, secret key
$iv = openssl_random_pseudo_bytes(16);  // Initialization Vector (IV)

// Data to be encrypted
$originalData = "Hello, this is a secret message.";

// Encrypt the data
$encryptedData = encryptData($originalData, $key, $iv);

echo "Encrypted: " . $encryptedData . "<br>";

// Decrypt the data
$decryptedData = decryptData($encryptedData, $key, $iv);

echo "Decrypted: " . $decryptedData . "<br>";
?>

Remember to replace "your_secret_key" with a strong and secret key. The $iv (Initialization Vector) is a random value used to ensure that the same plaintext encrypted with the same key will produce different ciphertexts.

This is a basic example, and in a production environment, you should handle key management securely, possibly using a dedicated key management service. Also, consider using authenticated encryption for better security.

Useful Tags :