S
S
Sergey2020-02-26 22:04:01
PHP
Sergey, 2020-02-26 22:04:01

How to catch an SSL error on an unsuccessful attempt to connect / stream_socket_client?

There was a task to catch (not just mute) errors that can occur when calling stream_socket_client. Issues with DNS/direct socket connection/etc. are caught through $errno and $errstr, but if an error occurs inside SSL, then $errno and $errstr are empty. I tried to look in openssl_error_string () - there are also zeros there. The actual test code:

$context = stream_context_create([
    'ssl' => [
        'capture_peer_cert'     => true,
        'verify_peer'           => false,
        'allow_self_signed'     => true,
        'SNI_enabled'           => true,
    ]
]);


$stream = stream_socket_client('ssl://localhost:80', $errno, $errstr, 30,
    STREAM_CLIENT_CONNECT, $context);

if ($stream === FALSE) {
    print "Connection error: errno:$errno errstr:$errstr\n";
    while($err = openssl_error_string()) {
        print "SSL Error: $err\n";
    }
    exit;
}



PHP Warning: stream_socket_client(): SSL operation failed with code 1. OpenSSL Error messages:
error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol in /tmp/ssl_t.php on line 15
PHP Warning: stream_socket_client(): Failed to enable crypto in /tmp/ssl_t.php on line 15
PHP Warning: stream_socket_client(): unable to connect to ssl://localhost:80 (Unknown error) in /tmp/ssl_t.php on line 15
Connection error: errno:0 errstr:


Actually the task: to extinguish the warning through @ and the error (and preferably all 3 warnings) "error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol" somehow catch in the code

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nokimaro, 2020-02-26
@Partiz

You can use your error_handler to intercept warnings in the place where an error can occur
https://www.php.net/manual/ru/function.set-error-h...
And then restore the standard error_handler if necessary
https:/ /www.php.net/manual/en/function.restore-err...

set_error_handler(function($errno, $errstr, $errfile, $errline){
    //своя логика обработки $errno, $errstr 
});

//$stream = stream_socket_client( ...

restore_error_handler();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question