2011-07-16 33 views

回答

2

改爲使用cURL。它允許更好的控制,並讓你閱讀任何檢索到的內容和狀態碼。

61

你必須configure the stream wrapper忽略的錯誤:

ignore_errorsboolean取甚至失敗狀態代碼的內容。默認爲FALSE

換句話說,做

echo file_get_contents(
    'http://stackoverflow.com/foo/bar', 
    false, 
    stream_context_create(
     array(
      'http' => array(
       'ignore_errors' => true 
      ) 
     ) 
    ) 
); 

,你會得到404頁。

如果你想這是對HTTP流的默認行爲,使用HTTP流包裝將使用這些設置,然後,例如使用

stream_context_set_default(
    array('http' => array(
     'ignore_errors' => true) 
    ) 
); 

任何調用你可以簡單地做

echo file_get_contents('http://stackoverflow.com/foo/bar'); 

如果你也想獲得response header,只是做

print_r($http_response_header); 

電話後。每次使用http流包裝器調用後,該變量將被重新填充(重新填充)。

+0

有趣的方法:通過將一個錯誤控制操作員(即@)在呼叫的前向的file_get_contents()抑制警告 - 但是你能否告訴你是否有錯誤或成功的迴應? – sagi

+0

@sagi響應代碼將在'$ http_reponse_header'中 – Gordon

+1

+1 Gordon是正確的,變量$ http_response_header包含它在罐子上所描述的內容,這明顯包括狀態碼。 –

0

步驟1:檢查返回代碼: $content = file_get_contents("websitelink"); if($content === FALSE) { // handle error here... }

步驟2:$content = @file_get_contents($site);

相關問題