Skip to content
PHP Logo

What is the process for creating a certificate for SSL encryption using PHP and OpenSSL?

When creating a certificate for SSL encryption using PHP and OpenSSL, you can use the `openssl_pkey_new()` function to generate a new private key and then use the `openssl_csr_new()` function to create a certificate signing request (CSR). Finally, you can use the `openssl_csr_sign()` function to sign the CSR with a self-signed certificate and generate the SSL certificate.

php
// Generate a new private key
$privateKey = openssl_pkey_new();

// Generate a CSR
$csr = openssl_csr_new(
    array(
        "commonName" => "example.com",
        "organizationName" => "Example Company",
    ),
    $privateKey
);

// Sign the CSR with a self-signed certificate
$cert = openssl_csr_sign($csr, null, $privateKey, 365);

// Save the private key and certificate to files
openssl_pkey_export($privateKey, $privateKeyOut);
file_put_contents("private_key.pem", $privateKeyOut);

openssl_x509_export($cert, $certOut);
file_put_contents("certificate.pem", $certOut);