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

时间:2013-11-02 10:47:43

标签: php sockets error-handling fgets

我有一个打开套接字连接的代码。有时会发生fgets返回false。我想知道它为什么会发生。是否有一个函数可以提供有关$handle上一次错误的更多详细信息?类似于preg_last_errorjson_last_error,...

同样的问题可以应用于函数stream_get_line()

我使用PHP 5.4并且E_ALL在error_reporting中(即它甚至包括E_NOTICE)。没有抛出任何错误。

2 个答案:

答案 0 :(得分:1)

注意这是未经测试的代码。我没有安装PHP来试试。

您应该可以使用 contexts 执行此操作,这是您在设置连接时创建的。

$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现在应该在发生错误时调用错误处理程序。

对不起,我现在无法测试这个...

答案 1 :(得分:0)

可以使用stream_get_meta_data()检索有关流的更多信息。但是,我通过重写代码以使用socket_*函数解决了这个问题。 API提供socket_last_error功能,这有很多帮助。