What is the purpose of using the mcrypt function in PHP for encryption?

The mcrypt function in PHP is used for encryption to secure sensitive data such as passwords, credit card numbers, and personal information. It helps to protect this data from unauthorized access by converting it into an unreadable format that can only be decrypted with the correct key. By using mcrypt, developers can ensure that data is securely transmitted and stored, reducing the risk of data breaches and privacy violations.

// Encrypt a string using mcrypt
function encryptData($data, $key) {
    $encrypted_data = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $data, MCRYPT_MODE_CBC, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC), MCRYPT_RAND));
    return base64_encode($encrypted_data);
}

// Decrypt an encrypted string using mcrypt
function decryptData($data, $key) {
    $data = base64_decode($data);
    $decrypted_data = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $data, MCRYPT_MODE_CBC, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC), MCRYPT_RAND));
    return rtrim($decrypted_data, "\0");
}

$data = "Sensitive data to encrypt";
$key = "SecretKey123";

$encrypted_data = encryptData($data, $key);
echo "Encrypted data: " . $encrypted_data . "\n";

$decrypted_data = decryptData($encrypted_data, $key);
echo "Decrypted data: " . $decrypted_data;