2010-08-04 72 views
5

這是我放在一起的PHP腳本的一部分。基本上,域($ domain1)在表單中定義,並根據服務器的響應代碼顯示不同的消息。但是,我遇到問題需要解決。 3位響應代碼都是我感興趣的獲取標題響應代碼

這是我到目前爲止有:。

function get_http_response_code($domain1) { 
    $headers = get_headers($domain1); 
    return substr($headers[0], 9, 3); 
    foreach ($get_http_response_code as $gethead) { 
     if ($gethead == 200) { 
      echo "OKAY!"; 
     } else { 
      echo "Nokay!"; 
     } 
    } 
} 
+0

看起來你在那裏有一些有趣的縮進/大括號。 – Zaz 2010-08-04 17:29:19

+0

你有什麼問題?請粘貼您收到的任何相關錯誤。另外,假設你粘貼的代碼準確地反映了你的腳本,那麼你的'return'語句下面的代碼都不會執行。 – 2010-08-04 17:30:22

回答

14
$domain1 = 'http://google.com'; 

function get_http_response_code($domain1) { 
    $headers = get_headers($domain1); 
    return substr($headers[0], 9, 3); 
} 

$get_http_response_code = get_http_response_code($domain1); 

if ($get_http_response_code == 200) { 
    echo "OKAY!"; 
} else { 
    echo "Nokay!"; 
} 
+0

很好,謝謝:) – Batfan 2010-08-04 18:32:58

+0

工作對於大多數事情,但是如果網站發送重定向,那麼重定向代碼是第一個,即'$ headers [0] = 301; $ headers [5] = 404'這可能意味着它工作或不工作。 – mt025 2017-12-01 01:27:45

6

如果你有PHP 5.4.0+您可以使用http_response_code()功能。例如:

var_dump(http_response_code()); // int(200) 
+0

不知道爲什麼你回答2年的問題(這是2年前回答),但是,感謝信息:) – Batfan 2013-06-03 16:44:46

+3

哦,我正在尋找一個http響應代碼相關的解決方案,並打開此線程。我發佈這個以防有人在這裏以某種方式到達。最好的祝福! – andufo 2013-06-03 17:22:47

+2

'http_response_code()'用於設置傳出代碼(例如瀏覽器),不檢查傳入代碼(來自服務器),這是OP想要做的事情。 – 2014-10-25 00:43:31

0

這裏是我的誰需要發送電子郵件時關閉服務器的人的解決方案:

$url = 'http://www.example.com'; 

while(true) { 

    $strHeader = get_headers($url)[0]; 

    $statusCode = substr($strHeader, 9, 3); 

    if($statusCode != 200) { 
     echo 'Server down.'; 
     // Send email 
    } 
    else { 
     echo 'oK'; 
    } 

    sleep(30); 
} 
0

你直接返回所以功能不會執行你寫的foreach進一步情況。它總是更好地保持兩個功能。

function get_http_response_code($domain1) { 
    $headers = get_headers($domain1); 
    return substr($headers[0], 9, 3); //**Here you should not return** 
    foreach ($get_http_response_code as $gethead) { 
     if ($gethead == 200) { 
      echo "OKAY!"; 
     } else { 
      echo "Nokay!"; 
     } 
    } 
}