2014-07-05 73 views
-2

我有問題,這個劇本,如果我檢查http://google.com/或其他網站未與http://stackoverflow.com工作,或cnn.com是工作...檢查部位是向上或向下

$url = 'http://google.com/'; 

function urlExists($url=NULL) 
{ 
    if($url == NULL) return false; 
    $ch = curl_init($url); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 10); 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    $data = curl_exec($ch); 
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
    curl_close($ch); 
    if($httpcode>=200 && $httpcode<300){ 
     return true; 
    } else { 
     return false; 
    } 
} 

if(urlExists($url)) 
{ 
    echo "ok"; 
} 
else 
{ 
    echo "no"; 
} 

我有測試@fopen和不工作太

像谷歌網站有阻滯劑?由於

回答

0

你應該改變:

if($httpcode>=200 && $httpcode<300){ 

到:

if($httpcode>=200 && $httpcode<303){ 

的原因是,很多網站默認使用一個301 Moved Permanently以及302 Found

+0

得益於與谷歌是好的,但與其他網站我有代碼403,這是好嗎?如果($ httpcode> = 200 && $ httpcode <= 403)? – user3710519

+0

你也可以上到404(儘管它真的取決於腳本的意圖)。你也可以做一些事情,比如'if($ httpcode = 200 || $ httpcode = 301 || $ httpcode = 403)'等等,下面是狀態代碼:http://www.w3.org/Protocols/rfc2616/ rfc2616-sec10.html –

+0

謝謝你的傢伙,並感謝所有的工作好:) – user3710519

0

您正在捲曲http://google.com,它響應代碼301來重定向訪問者http://www.google.com。在您的邏輯中,301響應代碼被視爲離線。

您需要調整您檢查的URL,調整邏輯以接受此響應代碼,或者添加以下代碼以使cURL跟隨重定向。

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
+0

謝謝我添加此 – user3710519

0

它也許應該讀

if($httpcode>=200 && $httpcode<400){ 

,而不是

if($httpcode>=200 && $httpcode<300){ 

否則,重定向會被視爲「服務器停機」。

對於上述變化,http://google.com結果是ok