Skip to content

Instantly share code, notes, and snippets.

@bohwaz
Last active September 15, 2023 05:41
Show Gist options
  • Save bohwaz/a3e4eb91e82f12768b69f8d24cf0cca8 to your computer and use it in GitHub Desktop.
Save bohwaz/a3e4eb91e82f12768b69f8d24cf0cca8 to your computer and use it in GitHub Desktop.
Check if certificate expiry is in more than 30 days
<?php
$domain = 'mydomain.tld';
if (get_ssl_certificate_expiry($domain) < 30) {
throw new \Exception('Certificate expires in less than 30 days!');
}
function get_ssl_certificate_expiry(string $domain): ?int
{
$get = stream_context_create(array("ssl" => array("capture_peer_cert" => TRUE)));
$read = stream_socket_client(sprintf("ssl://%s:443", $domain), $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);
}
@CViniciusSDias
Copy link

I assume it should be:

- if (get_ssl_certificate_expiry($domain) < >30) {
+ if (get_ssl_certificate_expiry($domain) < 30) {

@bohwaz
Copy link
Author

bohwaz commented Sep 14, 2023

Absolutely, thanks @CViniciusSDias :) I just typed this code quickly for this gist as the function is part of a larger script :)

@MircoBabin
Copy link

Because this initiative comes from the php #externals mailinglist, I thought I also share my solution. Because I also have to check certificate expiration dates for websites.

https://gist.github.com/MircoBabin/5c420c277b5a039df76c0469ed04c491

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment