How do I encrypt a string in PHP?

How do I encrypt a string in PHP?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How do I encrypt a string in PHP?

Implementing encryption requires moving beyond simple obfuscation to actual cryptographic security. The most common pitfall developers encounter is treating encryption like password hashing or using weak algorithms that are easily reverse-engineered. When you write a function expecting a secret key, as shown in your request, you must decide immediately whether you need asymmetric cryptography (public/private keys) or symmetric cryptography (a shared secret). For most application-level data protection, symmetric encryption using the Advanced Encryption Standard (AES) is the standard choice.

In modern PHP development, you should never roll your own cryptographic primitives. The built-in openssl_encrypt() and openssl_decrypt() functions provide access to industry-standard algorithms like AES-256-CBC or AES-GCM without requiring external dependencies. These functions handle the complex mathematics of block ciphers securely, whereas a custom implementation might introduce subtle bugs that compromise confidentiality.

Here is how you can structure a secure encryption function in PHP using AES-256-CBC:

function encrypt($string, $key) {
    $cipher = 'aes-256-cbc';
    
    // Generate a random IV (Initialization Vector) for this specific operation.
    // The IV must be random and unique for every encryption operation, even if the key is the same.
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher));
    
    // Encrypt the data
    $encrypted = openssl_encrypt(
        $string, 
        $cipher, 
        $key, 
        OPENSSL_RAW_DATA, 
        $iv
    );
    
    if ($encrypted === false) {
        throw new Exception('Encryption failed');
    }

    // Combine IV and encrypted data so they can be sent together.
    // The IV is public information needed for decryption, but it must be unique per message.
    return $iv . base64_encode($encrypted);
}

function decrypt($data, $key) {
    $cipher = 'aes-256-cbc';
    
    try {
        // Split the IV and the encrypted data
        $iv = substr($data, 0, openssl_cipher_iv_length($cipher));
        $encryptedData = base64_decode(substr($data, openssl_cipher_iv_length($cipher)));
        
        if ($encryptedData === false) {
            throw new Exception('Invalid base64 encoded data');
        }

        // Decrypt the data
        $decrypted = openssl_decrypt(
            $encryptedData, 
            $cipher, 
            $key, 
            OPENSSL_RAW_DATA, 
            $iv
        );

        if ($decrypted === false) {
            throw new Exception('Decryption failed');
        }

        return $decrypted;
    } catch (Exception $e) {
        // Handle decryption errors gracefully, e.g., wrong key or corrupted data
        throw new Exception('Decryption failed: ' . $e->getMessage());
    }
}

A critical detail often overlooked is the Initialization Vector (IV). In CBC mode, the IV ensures that encrypting the same plaintext with the same key produces different ciphertexts every time. This property is essential for semantic security; without it, an attacker could detect patterns in the data. The code above generates a fresh random IV for every call to encrypt(). This IV must be prepended to the encrypted output because it is required during decryption but does not need to be secret.

Another vital consideration is the handling of the secret key. Storing a static string like "mastermind" directly in your source code defeats the purpose of encryption if that file is ever committed to a version control system or leaked. In production environments, this key should be loaded from environment variables or a dedicated secrets manager. Furthermore, the key must be at least 256 bits long when using AES-256. If you are using a shorter string as your "key," PHP will automatically pad it or hash it, but relying on default behavior without understanding the underlying requirements is risky. Always ensure the entropy of your master key is sufficient to resist brute-force attacks.

For projects built on the Laravel framework, the Illuminate\Encryption facade abstracts much of this complexity, allowing you to define encryption keys and cipher modes in a single configuration file rather than hardcoding them in application logic. This approach integrates seamlessly with existing security practices and reduces the surface area for human error.

Our network