Skip to content

Instantly share code, notes, and snippets.

@bohwaz
Created September 8, 2022 15:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bohwaz/d6db90b40f0d201fe82bbaa9391ccf23 to your computer and use it in GitHub Desktop.
Save bohwaz/d6db90b40f0d201fe82bbaa9391ccf23 to your computer and use it in GitHub Desktop.
PHP function to get number of days before SSL/TLS certificate expiry from a HTTPS URL
<?php
/**
* Return number of days before certificate expiry from a HTTPS URL
* Usage: get_ssl_certificate_expiry('https://www.framasoft.net/')
* => int(45)
* @author bohwaz
*/
function get_ssl_certificate_expiry(string $url): ?int
{
$url = parse_url($url);
if ($url['scheme'] != 'https') {
return null;
}
$get = stream_context_create(array("ssl" => array("capture_peer_cert" => TRUE)));
$read = stream_socket_client(sprintf("ssl://%s:443", $url['host']), $errno, $errstr, 5, STREAM_CLIENT_CONNECT, $get);
$cert = stream_context_get_params($read);
if (!isset($cert['options']['ssl']['peer_certificate'])) {
return 0;
}
$certinfo = openssl_x509_parse($cert['options']['ssl']['peer_certificate']);
$date = $certinfo['validTo_time_t'] ?? null;
if (!$date) {
return 0;
}
return intval(($date - time()) / 3600 / 24);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment