This function not only checks whether the domain has an SSL certificate, but also confirms whether the certificate matches the requested domain.
The most important part is the openssl_x509_parse function, which parses the certificate and returns all the details as an array.
function has_ssl( $domain ) { $res = false; $stream = @stream_context_create( array( 'ssl' => array( 'capture_peer_cert' => true ) ) ); $socket = @stream_socket_client( 'ssl://' . $domain . ':443', $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $stream ); // If we got a ssl certificate we check here, if the certificate domain // matches the website domain. if ( $socket ) { $cont = stream_context_get_params( $socket ); $cert_ressource = $cont['options']['ssl']['peer_certificate']; $cert = openssl_x509_parse( $cert_ressource ); // Expected name has format "/CN=*.yourdomain.com" $namepart = explode( '=', $cert['name'] ); // We want to correctly confirm the certificate even // for subdomains like "www.yourdomain.com" if ( count( $namepart ) == 2 ) { $cert_domain = trim( $namepart[1], '*. ' ); $check_domain = substr( $domain, -strlen( $cert_domain ) ); $res = ($cert_domain == $check_domain); } } return $res; }
source share