2014-12-06 128 views
1

我想找到一種方法來處理任何4xx和5xx錯誤狀態代碼拋出像Apache 404錯誤的URL。我只想在服務器沒有拋出錯誤狀態碼的情況下執行if語句的內容。PHP的URL錯誤處理

使用以下if語句,似乎即使未找到託管內容並拋出Apache 404錯誤,它仍然運行if語句的內容。

if (@fopen('http://example','r')){ 
      use resource 
} 
else{ 
use other resources 
} 

有沒有更好的方法來確保網址在運行之前可用?

編輯: 我不能在這種情況下使用捲曲。

謝謝

+0

使用捲曲,使HEAD電話嗎? – 2014-12-06 03:47:33

+0

有沒有這樣的事情作爲錯誤,只有狀態代碼需要url返回。 – Yang 2014-12-06 03:47:34

+0

我不能使用捲曲,我希望我可以。我的印象是,4xx和5xx狀態碼稱爲錯誤狀態碼。對不起,我應該更清楚。 – bakingsoda 2014-12-06 03:53:20

回答

0
$headers = get_headers($url, 1); 
    if ($headers[0] == 'HTTP/1.1 200 OK') {//no error status codes thrown by the server 
    $data = file_get_contents($url); 
    //Do something 
    } 
0

使用此。

$headers = @get_headers($url, 1); 
    if ($headers[0] == 'HTTP/1.1 200 OK') { 
    //valid 
    } 
    if($headers[0] == 'HTTP/1.1 404 Not Found') { 
    // not found 
    } 
    if ($headers[0] == 'HTTP/1.1 301 Moved Permanently') { 
    //moved or redirect page 
    } 

get_headers()手冊:http://php.net/manual/en/function.get-headers.php