2012-10-25 77 views
0

我有一个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的事件。

我有一个关于这几个主要问题:

  1. Content-Type检查并不总是正确,因为指数并不总是7 GET请求。是我该循环在整个$http_response_headerstrstrContent-Type,然后检查呢?对我来说似乎很笨拙。该manual page对这个几乎没有。必须有一个更简单的方法来处理?

  2. 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,但可能会抑制其它警告我可能需要知道,我无法预测。有没有办法在这个函数中抑制这个特定的警告?

回答

1

根据this的问题,您可以从$_SERVER["CONTENT_TYPE"]超全球(我没有检查,所以我不能确定)content-type标题。编辑:现在已经检查,它似乎只适用于POST请求。

file_get_contents问题,你可能也抑制了警告,如果你不想要它,你可以明确地测试,如果它返回false。

只是说明;在一个函数中定义一个函数并不是一个好主意 - 如果在同一个脚本中调用TryGetJSON函数两次,你将会得到一个错误,因为你不能定义一个与已经定义的函数同名的函数。

相关问题