2009-11-12 117 views

回答

8
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); 
curl_setopt($ch, CURLOPT_HEADER, true); 
curl_setopt($ch, CURLOPT_NOBODY, true); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
curl_setopt($ch, CURLOPT_MAXREDIRS, 10); //follow up to 10 redirections - avoids loops 
$data = curl_exec($ch); 
curl_close($ch); 
if (!$data) { 
    echo "Domain could not be found"; 
} 
else { 
    preg_match_all("/HTTP\/1\.[1|0]\s(\d{3})/",$data,$matches); 
    $code = end($matches[1]); 
    if ($code == 200) { 
    echo "Page Found"; 
    } 
    elseif ($code == 404) { 
    echo "Page Not Found"; 
    } 
} 
here的代碼

修改版本。

1

我最近在尋找相同的信息。發現了一些非常好的代碼在這裏:http://php.assistprogramming.com/check-website-status-using-php-and-curl-library.html

function Visit($url){ 

    $agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"; 
    $ch = curl_init(); 
    curl_setopt ($ch, CURLOPT_URL,$url); 
    curl_setopt($ch, CURLOPT_USERAGENT, $agent); 
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt ($ch,CURLOPT_VERBOSE,false); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 5); 
    $page=curl_exec($ch); 
    //echo curl_error($ch); 
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
    curl_close($ch); 




    if($httpcode >= 200 && $httpcode < 300){ 
     return true; 
    } 
    else { 
     return false; 
    } 

} 

    if(Visit("http://www.site.com")){ 
     echo "Website OK"; 
    } 
    else{ 
     echo "Website DOWN"; 
    } 
+0

'304 Not Modified','307 Temporary Redirect',等等? – nickf 2009-11-12 14:49:29

+0

@nickf - 在捲曲獲取的上下文中,「304未修改」是否相關?我不知道curl發送了什麼頭文件 - 假設它不發送除您指定的內容以外的任何內容,服務器如何知道自上次請求它之後頁面是否已被修改? – 2009-11-12 14:51:52

2

我喜歡捲曲或到的fsockopen解決這個問題。任何一個人都可以提供有關所請求文件狀態的標題數據。具體來說,你會找一個404(文件未找到)響應。下面是我用的fsockopen使用的例子:

http://www.php.net/manual/en/function.fsockopen.php#39948

+2

當然,這應該是404「未找到」,而不是404「未找到文件」 – 2009-11-12 14:49:00

2

該函數將返回響應代碼(最後一個重定向的情況下),或者虛假的DNS或其它錯誤的情況下。如果提供了一個參數(url),則會發出HEAD請求。如果給出第二個參數,則完成一個完整的請求,響應的內容(如果有的話)通過引用存儲在作爲第二個參數傳遞的變量中。

function url_response_code($url, & $contents = null) 
{ 
    $context = null; 
    if (func_num_args() == 1) { 
     $context = stream_context_create(array('http' => array('method' => 'HEAD'))); 
    } 
    $contents = @file_get_contents($url, null, $context); 
    $code = false; 
    if (isset($http_response_header)) { 
     foreach ($http_response_header as $header) { 
      if (strpos($header, 'HTTP/') === 0) { 
       list(, $code) = explode(' ', $header); 
      } 
     } 
    } 
    return $code; 
} 
0

只需注意,這些解決方案在無法針對未找到頁面給出適當響應的網站上無法正常工作。例如,我在測試網站上的頁面時遇到問題,因爲它只是在獲取無法處理的請求時加載主站點頁面。因此,即使對於不存在的網頁,該網站也幾乎總是會提供200個響應。

有些網站會在標準頁面上提供自定義錯誤,但不會提供404頭。

在這些情況下你可以做的事情並不多,除非你知道頁面的預期內容,並開始測試預期的內容是否存在,或者測試頁面中的一些預期的錯誤文本,並且這一切都變得有點麻煩......

+0

如果可能,請嘗試添加一些對您的解釋的引用。 – DontVoteMeDown 2013-06-18 13:26:06