如何获取函数stream_get_line和fgets的错误?

I have a code where I open a socket connection. From time to time it happens that fgets returns false. I would like to find out why it happens. Is there a function that would provide more details about last error on $handle? Something like preg_last_error, json_last_error, …

The same question can be applied to function stream_get_line().

I use PHP 5.4 and E_ALL is in error_reporting (i.e. it includes even E_NOTICE). No error was thrown.

More information about stream can be retrieved by using stream_get_meta_data(). However, I solved the issue by rewriting my code to use socket_* functions. The API provides socket_last_error function which helps a lot.

NB this is untested code. I haven't got an installation of PHP to try it out on.

You should be able to do this with contexts, which you create when you set the connection up.

$context = stream_context_create();
stream_context_set_params(
    $context, 
    array(
        'notification' => function(
            $notification_code,
            $severity,
            $message,
            $message_code
        ) {
            switch ($notification_code) {
            case: STREAM_NOTIFY_FAILURE
                print_r(array(
                    'message' => $message,
                    'message_code' => $message_code,
                ));
                break;
            }
        },
    )
);

$socket = stream_socket_client ($remote_socket, &$errno, &$errstr, ini_get("default_socket_timeout"), STREAM_CLIENT_CONNECT, $context);

fgets should now call the error handler whenever an error occurs.

I'm sorry I can't test this at the moment...