c.cem dogan.← Back to journal
TECHNOLOGY

Collecting SSL expiration information.

Originally published in 2017. This historical example is reproduced as displayed on the original site; its formatting, syntax, and date calculations need review before use.

This small function gathers expiration information from an SSL certificate and calculates the days remaining until it expires. You can query multiple domains by calling get_cert_exp in a loop.

Enjoy!

<?php

function get_cert_exp($url){
$orignal_parse = parse_url($url, PHP_URL_HOST);
$get = stream_context_create(array(“ssl” => array(“capture_peer_cert” => TRUE)));
$read = stream_socket_client(“ssl://”.$orignal_parse.”:443″, $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $get);
$cert = stream_context_get_params($read);
$certinfo = openssl_x509_parse($cert[‘options’][‘ssl’][‘peer_certificate’]);

//$expired= getdate($certinfo[validTo]);
$end=($certinfo[validTo]);
$end=substr($end, 0, -1); //remove last char from string
$chunks = str_split($end, 2);
//Convert array to string. Each element separated by the given separator.
$expire_date = implode(‘:’, $chunks);
$expire_date=’20’.$expire_date;

// Days left to expire date //
$gd_a = getdate( $certinfo[‘validTo_time_t’] );
$gd_b = getdate( time() );

$a_new = mktime( 12, 0, 0, $gd_a[‘mon’], $gd_a[‘mday’], $gd_a[‘year’] );
$b_new = mktime( 12, 0, 0, $gd_b[‘mon’], $gd_b[‘mday’], $gd_b[‘year’] );

$days_left=round( abs( $a_new – $b_new ) / 86400 );
// end of calculation //
if ($days_left <= 50 ) {
$days_left=”<b><font color=red>”.$days_left.”</font></b>”;
}else{
$days_left=”<b><font color=green>”.$days_left.”</font></b>”;
}

echo “SSL Certificate of <b> $url </b>is valid until “.$expire_date.'</br>’;
echo “Days remaining until expiration : “. $days_left.'</br>’;
}

get_cert_exp(“https://your.nice.expiring.domain/”);

?>
← Back to journal