Are there any built-in PHP functions that can be used for string encryption instead of custom implementations?

Yes, PHP provides built-in functions like `openssl_encrypt` and `openssl_decrypt` that can be used for string encryption and decryption. These functions use strong encryption algorithms and are recommended for secure encryption needs. By using these built-in functions, you can avoid the pitfalls of implementing custom encryption methods that may not be as secure.

// Encrypt a string using openssl_encrypt
function encryptString($string, $key) {
    $method = 'AES-256-CBC';
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
    $encrypted = openssl_encrypt($string, $method, $key, 0, $iv);
    return base64_encode($iv . $encrypted);
}

// Decrypt an encrypted string using openssl_decrypt
function decryptString($string, $key) {
    $method = 'AES-256-CBC';
    $data = base64_decode($string);
    $iv = substr($data, 0, openssl_cipher_iv_length($method));
    $encrypted = substr($data, openssl_cipher_iv_length($method));
    return openssl_decrypt($encrypted, $method, $key, 0, $iv);
}

// Example usage
$key = 'secret_key';
$originalString = 'Hello, World!';
$encryptedString = encryptString($originalString, $key);
$decryptedString = decryptString($encryptedString, $key);

echo "Original String: $originalString\n";
echo "Encrypted String: $encryptedString\n";
echo "Decrypted String: $decryptedString\n";