2017-01-23 69 views
0

使用file_get_contents()当我得到403错误,如何处理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 
} 

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

有什么想法?

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

+0

我相信你有一个错字在required_functionü忘记修正正 –

+0

,这是我从你们所需要的功能:)如果可能的话 –

+0

哦,好的,我个人从来没有处理一个403 ...但我知道你可以处理404从.htaccess它重定向到一个自定义页面...也许尝试吗? –

回答

0

我个人建议你使用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扩展没有这个限制。

+0

我同意这个答案试一下 –

+0

if(get_headers($ url)[0] ==“HTTP/1.1 403 FORBIDDEN”)会正常工作吗? –

+0

谢谢@TuğcaEker –

0

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

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

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

问:如何在响应中检索http状态?
答:经过file_get_contents()函数调用,评估$ http_response_header

问:如何检索响应体甚至错误HTTP响应代码?
答:设置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;