php - 如何处理 file_get_contents() 中的 403 错误?

标签 php error-handling

我在使用 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 错误,脚本就不会崩溃。

有什么想法吗?

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

最佳答案

我个人建议您使用 cURL 而不是 file_get_contents。 file_get_contents 非常适合面向基本内容的 GET 请求。但是 header 、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

Warning about $http_response_header, (from php.net)

Note that the HTTP wrapper has a hard limit of 1024 characters for the header lines. Any HTTP header received that is longer than this will be ignored and won't appear in $http_response_header. The cURL extension doesn't have this limit.

关于php - 如何处理 file_get_contents() 中的 403 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41802082/

相关文章:

javascript - Wordpress 的 Ajax 选项卡在用户更改选项卡时加载并运行不同的短代码

haskell - 可扩展错误

php - 如何使用 jQuery 将数据发布到 Laravel Controller 方法中

php - UPS API 包括正确的 WSDL 文件和端点

python - 出错时退出多处理程序

sql-server - 从vb.net调用具有已知错误的存储过程的错误处理

python - 在处理异常时,如何打印出现的任何错误声明?请参阅下面的更多细节

error-handling - 在extjs中如何全局处理错误

php - 如何在不使用 "counter"变量的情况下找出 PHP 中 foreach 构造循环的次数?

php - 使用多个值的内连接查询