繁体   English   中英

带有get请求的file_get_contents中的错误处理和内容类型

[英]error handling and content-type in file_get_contents with get request

我在这里有一个PHP函数:

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()未能从指定的URL检索JSON,则将其写入error_log 如果出现503它将重新尝试3次。

我对此有两个主要问题:

  1. Content-Type检查并不总是正确的,因为在GET请求中索引并不总是7。 我是否想使用strstr遍历整个$http_response_header以获得Content-Type ,然后进行检查? 在我看来笨拙。 手册页对此几乎没有任何内容。 必须有一个更简单的方法来解决这个问题?

  2. 我的error_log404上有这样的行:


[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上禁止显示,但这可能会禁止我可能需要了解的其他无法预测的警告。 有没有一种方法可以仅在此功能中禁止该特定警告?

根据问题,您可以从$_SERVER["CONTENT_TYPE"]超全局变量获取content-type标头(我尚未检查,因此无法确定)。 编辑:现在已检查,它似乎仅可用于POST请求。

对于file_get_contents问题,如果不想使用警告,也可以取消警告,并且可以显式测试警告是否返回false。

只是一个音符; 在函数中定义一个函数不是一个好主意-如果在同一脚本中两次调用TryGetJSON函数, TryGetJSON出错,因为您无法使用与已定义的相同名称来定义函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM