[PHP] How to get SSL certificate info from a remote server/port

This method uses streams and can be used on most ports/services, it is NOT restricted to web SSL’s or port 443.

Lets look at this code example below:

$contextCreate = stream_context_create(array("ssl" => array("capture_peer_cert" => true)));
$res = stream_socket_client("ssl://google.co.uk:443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $contextCreate);
$context = stream_context_get_params($res);
$certInfo = openssl_x509_parse($context["options"]["ssl"]["peer_certificate"]);

print_r($certInfo);

In the above example we create a stream to connect to google.co.uk on port 443. We then use the OpenSSL module to parse the certificate from the stream. Then we print the generated array, which contains information about the certificate.

The above example retrieves the SSL certificate information for the certificate on port 443, which is the port for https:// web connections. If we wanted to, for example, retrieve the certificate information for a mail server we could change the domain/port as so:

$contextCreate = stream_context_create(array("ssl" => array("capture_peer_cert" => true)));
$res = stream_socket_client("ssl://imap.gmail.com:993", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $contextCreate);
$context = stream_context_get_params($res);
$certInfo = openssl_x509_parse($context["options"]["ssl"]["peer_certificate"]);

print_r($certInfo);

In this example we get the certificate information for the Gmail IMAP connection. We do this by changing the domain to imap.gmail.com (where Gmail allows IMAP connections) and changing the port to the IMAP SSL port, 993.

So rather than getting the web SSL certificate, we are parsing the SSL certificate that is made available to an IMAP client.

This process should work for all compliant SSL connections/services/ports.

You May Also Like

About the Author: trader418

Leave a Reply

Your email address will not be published. Required fields are marked *