我有一个PHP函数在这里:错误处理和内容类型中的file_get_contents与GET请求
function TryGetJSON($URL) { //Attempts to retrieve the JSON at a URL, script terminates if failure
function LogAndDie($msg) { error_log($msg); die(); }
for($attempt = 0; $attempt < 3; $attempt++) { //Try 3 times to fetch URL
$JSON = file_get_contents($URL); //Attempt to fetch, then check Response Header
if(!$JSON && isset($http_response_header) && strstr($http_response_header[0], '503'))
continue; //503 response: server was busy, so try again
else
break; //$JSON is populated, must be a 200 response
}//$JSON is always false on 404, file_get_contents always returns false on read failure
if(isset($http_response_header)) {
if(strstr($http_response_header[0], '503')) //If still 503, then all our attempts failed
LogAndDie('Could not get JSON file (' . $URL . '): ' . $http_response_header[0] . ' after 3 attempts.');
if(!strstr($http_response_header[0], '200')) //If not a 200
LogAndDie('Could not get JSON file (' . $URL . '): ' . $http_response_header[0]);
if(!strstr($http_response_header[7], 'application/json')) //Check Correct Content-Type
LogAndDie('Wrong Content Type for (' . $URL . '). Received: ' . $http_response_header[7]);
return $JSON;
}
if(!$JSON) LogAndDie('Could not get JSON file (' . $URL . ').'); //Catch all
}
功能的要点是,它die()
S和如果它不能检索JSON写入error_log
来自指定的网址。它重新尝试3次的503
的事件。
我有一个关于这几个主要问题:
的
Content-Type
检查并不总是正确,因为指数并不总是7 GET请求。是我该循环在整个$http_response_header
与strstr
为Content-Type
,然后检查呢?对我来说似乎很笨拙。该manual page对这个几乎没有。必须有一个更简单的方法来处理?我
error_log
有这样的线路上404
:
[25-Oct-2012 09:02:23] PHP Warning: file_get_contents(...) [<a href='function.file-get-contents'>function.file-get-contents</a>]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in ... on line 8
[25-Oct-2012 09:02:23] Could not get JSON file (...): HTTP/1.1 404 Not Found
我只保留矿井(第二行),而不是用填充我的error_log
感兴趣都。我发现@
可以用来抑制这种对file_get_contents
,但可能会抑制其它警告我可能需要知道,我无法预测。有没有办法在这个函数中抑制这个特定的警告?