【问题标题】:How to catch errors when using file_get_contents on an external URL在外部 URL 上使用 file_get_contents 时如何捕获错误
【发布时间】:2023-04-06 03:37:01
【问题描述】:

要从我的 PHP 代码向外部 url 发出 POST 请求,我使用以下 sn-p,在此处发布了许多主题:

function http_post($url, $data) {
    $options = ['http' => ['header' => "Content-type: application/x-www-form-urlencoded\r\n",'method' => 'POST','content' => http_build_query($data)]];
    $result = file_get_contents($url, false, stream_context_create($options));
    if ($result === FALSE) { /* Handle error */}
    return $result;
}

这可行,但我正在努力解决“处理错误”部分。我应该如何实现这个?更具体地说:

  • 如何获得错误的文本版本以存储在我的日志中?其中一些我当然可以通过将 file_get_contents 包含在 try-catch 块中来捕获,但是静默返回 false 的情况呢?
  • 我如何知道这是“超时”/“连接问题”类型的错误(在这种情况下我想再试一次)或“找不到网站”/“访问被拒绝”/等类型的错误。 (在这种情况下我不想再试一次)?

【问题讨论】:

标签: php file-get-contents


【解决方案1】:

file_get_contents() 的存在是为了简化它的使用,因此开发人员不必处理所有技术细节,例如检索的文件是在本地存储上还是通过网络检索。在某些情况下 file_get_contents() 很简单。

也许这个函数可以让您更深入地了解问题所在: https://www.php.net/manual/en/function.error-get-last.php

if (!$result = @file_get_contents($url, false, $context)) {
    $error = error_get_last();
    echo "Error: " . $error['message'];
}

如果您希望对请求及其响应有更多的权力,您可能需要查看其他库,例如 curl (https://www.php.net/manual/en/book.curl.php)

【讨论】:

    猜你喜欢
    • 2018-05-17
    • 1970-01-01
    • 2018-12-12
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 2015-06-04
    相关资源
    最近更新 更多