有沒有辦法在發送用戶之前檢查服務器是否響應錯誤代碼?在執行操作前檢查PHP中的重定向
目前,我基於來自後端的用戶可編輯輸入(客戶端請求,因此他們可以打印他們自己的域名,但將其他人發送給別人)重定向,但是我想檢查URL是否會實際響應,如果不是通過一條消息將它們發送到我們的主頁。
有沒有辦法在發送用戶之前檢查服務器是否響應錯誤代碼?在執行操作前檢查PHP中的重定向
目前,我基於來自後端的用戶可編輯輸入(客戶端請求,因此他們可以打印他們自己的域名,但將其他人發送給別人)重定向,但是我想檢查URL是否會實際響應,如果不是通過一條消息將它們發送到我們的主頁。
你可以用捲曲做到這一點:
$ch = curl_init('http://www.example.com/');
//make a HEAD request - we don't need the response body
curl_setopt($ch, CURLOPT_NOBODY, true);
// Execute
curl_exec($ch);
// Check if any error occured
if(!curl_errno($ch))
{
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); //integer status code
}
// Close handle
curl_close($ch);
然後,您可以檢查是否$ httpCode是OK。通常一個2XX響應代碼是可以的。
您可以嘗試以下操作,但要注意,這是對重定向的單獨請求,所以如果兩者之間出現問題,用戶仍然可能會被髮送到錯誤的位置。
$headers = get_headers($url);
if(strpos($headers[0], 200) !== FALSE) {
// redirect to $url
} else {
// redirect to homepage with error notice
}
爲get_headers()的PHP手冊:http://www.php.net/manual/en/function.get-headers.php
我不明白你的意思,確保網址會迴應。但是如果你想顯示一條消息,你可以使用一個$_SESSION
變量。請記住在每個將使用該變量的頁面上放置session_start()
。
所以當你想將它們重定向回主頁。你可以做到這一點。
// David Caunt's answer
$ch = curl_init('http://www.example.com/');
// Execute
curl_exec($ch);
// Check if any error occured
if(!curl_errno($ch))
{
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); //integer status code
// My addition
if($httpCode >= 200 && $httpCode < 300) {
// All is good
}else {
// This doesn't exist
// Set the error message
$_SESSION['error_message'] = "This domain doesn't exist";
// Send the user back to the home page
header('Location: /home.php'); // url based: http://your-site.com/home.php
}
// My addition ends here
}
// Close handle
curl_close($ch);
然後在你的主頁上,你會看到類似的東西。
// Make sure the error_message is set
if(isset($_SESSION['error_message'])) {
// Put the error on the page
echo '<div class="notification warning">' . $_SESSION['error_message'] . '</div>';
}
注意:不需要做一個完整的頁面請求,只有頭文件是好的,get_headers()提供這個作爲一個標準的PHP函數。不需要捲曲,這只是一個過於複雜。 – 2010-10-30 15:40:30
好點,我已經修改了我的答案,以提出HEAD請求! get_headers是一個可能的解決方案,但cURL功能更強大,可以像重定向一樣。 – 2010-10-30 16:08:51
結果get_headers()使用GET請求,所以你的方法是最好的:)但記錄get_headers()也遵循重定向。 – 2010-10-30 17:14:06