0

I have a code that checks if a website have SSL certificate as you can see below:

$url = "stackoverflow.com";
$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']);
var_dump($certinfo);

If I insert a url that contains HTTPS, this code return to me all the information about the certificate, but if I insert a url that doesn't contain HTTPS I receive the following error:

Warning: stream_socket_client (): Unable to connect to ssl: //: 443 (No connection could be made because the target machine actively refused it.) In

How I can solve this problem?

2
  • 1
    That error indicates the remote server is not listening on or is blocking connects to port 443 (SSL port). You need to handle that error appropriately and if you encounter it, you know the site doesn't support SSL. Commented Jul 22, 2016 at 0:13
  • Well, in this case I need to have another code to check the response of that request, and If the status code is <code>200</code> I execute my code, If not I don't execute that code and avoid the Warning... Commented Jul 22, 2016 at 15:34

1 Answer 1

1

You should be checking the return value of stream_socket_client() and if it returns false not proceeding any further (because the resource is not valid).

$url = "stackoverflow.com";
$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);

if (!$read) {
    // ssl connection failed for some reason
    // could be a certificate error or failure to connect on port 443
    echo "Failed to connect to site.  Error {$errno}: {$errstr}\n";
} else {
    $cert = stream_context_get_params($read);
    $certinfo = openssl_x509_parse($cert['options']['ssl']['peer_certificate']);
    var_dump($certinfo);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, your code works and now my problem is solved

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.