2009-09-03 45 views
0

我有一個名爲Error.php的頁面。通常使用查詢字符串將變量傳遞給它,以便它將相應的消息顯示給我已分配的錯誤代碼。顯示使用查詢字符串但沒有任何變量的頁面

?例如:Error.php ID = 1

這裏是我下面的網頁的部分:

<?php 
if($_GET["id"] == "0") 
{ 
    echo "Display certain information..."; 
} 
elseif($_GET["id"] == "1") 
{ 
    echo "Display certain information..."; 
} 
elseif($_GET["id"] == "2") 
{ 
    echo "Display certain information..."; 
} 
elseif($_GET["id"] == "3") 
{ 
    echo "Display certain information...";  
} 
else 
{ 
    echo "Display certain information..."; 
} 
?> 

所有信息工作正常,但唯一的問題是,如果沒有查詢字符串(將其保留爲「Error.php」),它會顯示錯誤,說明「未定義的索引:id在.....」。有沒有辦法讓Error.php不可訪問,除非有一個查詢字符串?如果我的代碼語法不正確,我很抱歉,我對PHP很陌生。謝謝。

回答

3

使用array_key_exists()來檢查,看看它的存在:

<?php 

if(array_key_exists("id", $_GET)) 
{ 
    if($_GET["id"] == "0") 
    { 
     echo "Display certain information..."; 
    } 
    elseif($_GET["id"] == "1") 
    { 
     echo "Display certain information..."; 
    } 
    elseif($_GET["id"] == "2") 
    { 
     echo "Display certain information..."; 
    } 
    elseif($_GET["id"] == "3") 
    { 
     echo "Display certain information...";  
    } 
    else 
    { 
     echo "Display certain information..."; 
    } 
} 
else 
{ 
    // no query id specified, maybe redirect via header() somewhere else? 
} 

?> 
+0

當我嘗試,我得到了一個錯誤: 致命錯誤:調用未定義功能array_has_key() – user 2009-09-03 08:38:24

+0

對不起,想起了函數名不正確了我的頭頂。我已經編輯了正確的函數來使用答案。 :) – Amber 2009-09-03 08:40:24

+0

謝謝。我最終使用最後的else語句來引用回主頁。非常感謝你! – user 2009-09-03 08:47:52

0

這消息是不是一個錯誤,但通知。您可以禁用Web應用程序中的通知消息,建議在進入生產服務時進行通知消息(在開發過程中可以正常使用)。

您可以通過設置在php.ini error_reporting這樣做不包括E_NOTICE

1

你應該如果變量在使用它之前存在,或者與issetarray_key_exists第一個測試:

if (isset($_GET['id'])) { 
    // $_GET['id'] exists 
    // your code here 
} else { 
    // $_GET['id'] does not exist 
} 
0

你應該使用isset來檢查數組$ _GET中是否設置了鍵'id'。對於簡單的字符串查找,您應該使用數組而不是if-then-else並切換。

$errorMessages = array(
    "0" => "Display certain information..."; 
    "1" => "Display certain information..."; 
    "2" => "Display certain information..."; 
    "3" => "Display certain information..."; 
); 

if (!isset($_GET['id']) || !isset($errorMessages[$_GET['id']])) { 
    $message = 'No predefined error message'; 
    //or redirect 
} else { 
    $message = $errorMessages[$_GET['id']]; 
} 
echo $message; 
相關問題