PHP function to get number of days before SSL/TLS certificate expiry from a HTTPS URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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