2

I have some code that makes a connection to public websites and returns information about the SSL certificate - code is working perfectly fine.

I would like to add an if statement where if the connection could not be established then it would return "could not establish connection".. right now, if it cannot connect it produces a whole heap of warnings.

The code responsible for making the socket connection is as follows

MAKE SOCKET CONNECTION

$ctx = stream_context_create( array("ssl" => $ssloptions) );
$result = stream_socket_client("ssl://$url:443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $ctx);
$cont = stream_context_get_params($result);

IF SOCKET CONNECTION FAILED

echo "could not establish connection"

IF CONNECTION SUCCESSFUL

foreach($cont["options"]["ssl"]["peer_certificate_chain"] as $cert) {
    openssl_x509_export($cert, $pem_encoded);
    echo $pem_encoded;
}

Appreciate the assistance.

user3436467
  • 1,763
  • 1
  • 22
  • 35
  • 1
    you want to use try / catch : http://php.net/manual/en/language.exceptions.php |--| http://php.net/manual/en/internals2.opcodes.catch.php – MuppetGrinder Apr 23 '15 at 11:51
  • @MuppetGrinder, not quite sure how to apply it - thanks for your suggestion. – user3436467 Apr 23 '15 at 12:22
  • See [this][1] previous thred to see how to use try / catch in php [1]: http://stackoverflow.com/questions/9041173/throwing-exceptions-in-a-php-try-catch-block – MuppetGrinder Apr 23 '15 at 12:33

1 Answers1

2
$ctx = @stream_context_create( array("ssl" => $ssloptions) );
$result = @stream_socket_client("ssl://$url:443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $ctx);

if($result == false) {
    echo "could not establish connection";
} else {
    $cont = @stream_context_get_params($result);
    foreach($cont["options"]["ssl"]["peer_certificate_chain"] as $cert) {
        openssl_x509_export($cert, $pem_encoded);
        echo $pem_encoded;
    }
}
Bhavesh G
  • 3,000
  • 4
  • 39
  • 66