簡體   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