【问题标题】:How to handle 403 error in file_get_contents()?如何处理 file_get_contents() 中的 403 错误?
【发布时间】:2017-01-23 08:40:11
【问题描述】:

我在使用 file_get_contents() 时遇到 403 错误,

我想这样处理这个错误,

if(required_function(file_get_contents($url))){  //detects there is a 403
    error
// do some special set of tasks
}else{
    //run normally
}

我试图读取错误,因为当我粘贴到浏览器中时 url 显示错误,但没有进入 file_get_contents() 所以我失败了。我不认为更改用户代理会起作用,因为系统可能仍然能够检测到这是一个脚本,所以我意识到如果我能检测到 403 错误,脚本就不会崩溃。

有什么想法吗?

请帮忙,我是编程新手。非常感谢。

【问题讨论】:

  • 我相信你在 required_function 中有错字你忘记了一个 n
  • 已更正,这就是我需要你们提供的功能 :) 如果可能的话
  • 哦,好吧,我个人从来没有处理过 403……但我知道你可以从 .htaccess 处理 404,让它重定向到自定义页面……也许试试?
  • 看看这个。这正是我认为你通过 .htaccess 文件处理它的原因。没有功能stackoverflow.com/a/11877381/7428715
  • 只需要从 url 获取数据,如果 url 给出 403 错误,脚本应该做一些其他的事情来防止它崩溃:)

标签: php error-handling


【解决方案1】:

我个人建议您使用 cURL 而不是 file_get_contents。 file_get_contents 非常适合面向基本内容的 GET 请求。但是标头、HTTP 请求方法、超时、重定向和其他重要的事情都无关紧要。

不过,要检测状态代码(403、200、500 等),您可以使用 get_headers() 调用或 $http_response_header 自动分配变量。

$http_response_header 是一个预定义变量,它会在每次 file_get_contents 调用时更新。

以下代码可能会直接为您提供状态代码(403、200 等)。

preg_match( "#HTTP/[0-9\.]+\s+([0-9]+)#", $http_response_header[0], $match);
$statusCode = intval($match[1]);

变量的更多信息和内容请查看官方文档

$http_response_header — HTTP response headers

get_headers — Fetches all the headers sent by the server in response to a HTTP request

(更好的选择)cURL

警告 $http_response_header, (from php.net)

请注意,HTTP 包装器有一个硬 标题行限制为 1024 个字符。接收到的任何长于此长度的 HTTP 标头都将被忽略,并且不会出现在 $http_response_header 中。 cURL 扩展没有这个限制。

【讨论】:

  • 我同意这个答案,先试试这个
  • if(get_headers($url)[0] =="HTTP/1.1 403 FORBIDDEN") 可以正常工作吗?
  • 是的,你给出的例子应该可以。我还编辑了我的答案并添加了一个直接给出请求状态代码的示例。您可能想使用它。此外,如果您认为此解决方案正确且具有解释性,请将其标记为正确答案。
  • 是的,我刚试过你的代码,它只给出 0 @TuğcaEker
  • 让我再检查一遍。
【解决方案2】:

我刚遇到类似的问题并解决了。我的解决方案涵盖更多案例:

问:如何在 PHP 中进行 POST,而不使用 cURL?
答:使用 file_get_contents()。

问:如何让 file_get_contents() 不报错 HTTP 状态?
A:在传递给 file_get_contents() 的选项中设置 ingore_errors=>TRUE。

问:如何在响应中检索 http 状态?
A:在 file_get_contents() 调用之后,评估 $http_response_header

问:即使是错误的http响应代码,如何检索响应正文?
A:设置 ignore_errors=>TRUE 并且 file_get_contents() 将返回正文。

下面是代码示例:

$reqBody = '{"description":"test"}';
$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => "Content-Type: application/json\r\n",
        'ignore_errors' => TRUE,
        'content' => $reqBody
    )
);

$context = stream_context_create($opts);
$url = 'http://mysite';
// with ignore_errors=true, file_get_contents() won't complain
$respBody = file_get_contents($url, false, $context);

// evaluate the response header, the way you want.
// In particular it contains http status code for response
var_dump($http_response_header);

// with ignore_errors=true, you get respBody even for bad http response code
echo $respBody;

【讨论】:

    猜你喜欢
    • 2019-02-01
    • 2015-07-05
    • 1970-01-01
    • 2016-02-14
    • 1970-01-01
    • 2012-08-06
    • 2019-01-13
    • 1970-01-01
    相关资源
    最近更新 更多