我在使用 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/