Skip to content

Simple example to get started

Stefan Körfgen edited this page Mar 7, 2024 · 5 revisions
<?php

// Simple example to get started

// This can be run by a cronjob for example (no need to time it exactly,
// just run it often enough). It checks if the already existing certificate
// needs to be renewed before making any connection to the CA

// Require ACMECert
require 'ACMECert/ACMECert.php';
use skoerfgen\ACMECert\ACMECert;

// Choose Certificate Authority (CA)

// Let's Encrypt Staging CA
$ac=new ACMECert('https://acme-staging-v02.api.letsencrypt.org/directory');

// Check if the previous certificate needs to be renewed (if there is one already)
if (file_exists(__DIR__.'/fullchain.pem')){
  $days=$ac->getRemainingDays('file://'.__DIR__.'/fullchain.pem');
  if ($days>30) { // renew 30 days before expiry
    echo 'Certificate still good, exiting..';
    exit();
  } 
}

// Check if account_key.pem exists. If not generate new key and
// register it with the CA and save it.
if (!file_exists(__DIR__.'/account_key.pem')){
  
  // Generate RSA Private Key
  $key=$ac->generateRSAKey(2048);
  
  // load new key into ACMECert
  $ac->loadAccountKey($key);
  
  // Register Account Key with CA
  $ac->register(true,'[email protected]');
  
  // Registration succeeded, save key to account_key.pem
  file_put_contents(__DIR__.'/account_key.pem',$key); 
}else{
  // load existing account key into ACMECert
  $ac->loadAccountKey('file://'.__DIR__.'/account_key.pem');
}


// Get Certificate using http-01 challenge
$domain_config=array(
  'test1.example.com'=>array('challenge'=>'http-01','docroot'=>'/var/www/vhosts/test1.example.com'),
  'test2.example.com'=>array('challenge'=>'http-01','docroot'=>'/var/www/vhosts/test2.example.com')
);

$handler=function($opts){
  $fn=$opts['config']['docroot'].$opts['key'];
  @mkdir(dirname($fn),0777,true);
  file_put_contents($fn,$opts['value']);
  return function($opts){
    unlink($opts['config']['docroot'].$opts['key']);
  };
};

// Generate new certificate key
$private_key=$ac->generateRSAKey(2048);

$fullchain=$ac->getCertificateChain($private_key,$domain_config,$handler);

// Success! Save the certificate chain and private key
file_put_contents(__DIR__.'/fullchain.pem',$fullchain);
file_put_contents(__DIR__.'/private_key.pem',$private_key);

// Reload the webserver
Clone this wiki locally