2012-07-18 170 views
0

以下基本代碼按預期工作。頁面未找到頁眉錯誤

<?php 
mysql_connect("localhost", "user", "[email protected]") or die(mysql_error()); 
echo "Connected to MySQL<br />"; 
?> 

什麼我需要的是,而不是mysql_error,頁面未找到404錯誤應該返回。 我正在尋找儘可能短的代碼,因爲這將被用作負載平衡器檢查。

以下似乎不起作用。我得到一個空白頁面。

mysql_connect("localhost", "user", "[email protected]") or die(header("HTTP/1.0 404 Not Found")); 
+1

一個空白頁,似乎一個很適當的響應。你在日誌中遇到錯誤嗎?你檢查過被返回的HTTP頭嗎? – deceze 2012-07-18 12:12:46

回答

1

我會做到以下幾點:牢記我使用mysqli的替代,使用mysql_的*強烈勸阻。

$mysqli = new mysqli('localhost', 'user', 'password', 'dbname'); 

if ($mysqli->connect_error) { 
    header("HTTP/1.0 404 Not Found"); 
} else { 

} 

您確定要返回404雖然,作爲資源已發現這是一個誤導,我將返回500錯誤作爲這將是更合適的服務器錯誤。

有關HTTP狀態代碼的列表,請參閱here

1

mysql_connect will return a false value if the connection was not successful.

$connected = mysql_connect("localhost", "user", "[email protected]"); 
if (!$connected){ 
    header("HTTP/1.0 404 Not Found"); 
} 

不知道你使用的正是這種代碼 - 但不能夠連接到你的數據庫並不一定意味着所請求的頁面不存在 - 它可能也是你的sql服務器的問題。


作爲一個附註 - 避免使用日期的mysql_ *函數。使用它們獲取新代碼的能力很強 discouraged。 更多現代化的替代品可供選擇並更好地維護。 考慮學習 prepared statements 改爲使用 PDO or MySQLi。 當嚴格使用時,避免繁瑣和手動轉義部分,因此變得更容易堆積,因爲副產品更安全使用。 請參閱a PDO tutorial開始。

+2

從什麼時候'mysql_ *'拋出異常? – deceze 2012-07-18 12:11:28

+0

@dec - 謝謝你 - 你的確是100%正確的...... – Lix 2012-07-18 12:13:25

1

使用庫MySQLi或PDO,mysql_ *將得到大幅貶值

$link =mysql_connect("localhost", "user", "[email protected]"); 
if (!$link) { 
    header("error.php"); 
} 
echo 'Connected successfully'; 
1

如果檢查我只想做一個並返回500錯誤,因爲如果谷歌試圖查看索引頁面,當您無法連接,並把它回404 ,它會認爲您的網站已損壞,您將失去排名並鏈接到該網頁。

500將至少表明,有一個服務器的問題,但是這將是固定:

if(!mysql_connect('localhost', 'user', 'pass')){ 
    header('HTTP/1.1 500 Server error'); 
    exit(); 
} 
+0

是否也可以像查看數據庫一樣檢查查詢時間,如果超過1秒就返回500錯誤? – shantanuo 2012-07-19 09:15:52