2011-08-28 43 views
2

我已經從HTML轉換到PHP編碼,所以當我想爲我的新聞頁面創建一個鏈接時,我使用HREF將該行的id作爲鏈接,並使該部分的標題成爲可見/點擊鏈接:確保信息後?是一個整數

echo "<a href=news.php?id=".$row{'id'}; 
echo ">"; 
echo ucwords(strtolower($row{'newstitle'})); 
echo "</a>"; 

所以,當有人點擊標題重定向文章和地址欄變成(顯然這是一個例子): http://site.com/news.php?id=1

我如何可以驗證後的信息?是id = int(它始終是一個數字),而不是一些用戶代碼或其他可能會損壞網站的輸入?我查看了消毒/驗證代碼的方法,但我發現的所有示例都是將信息輸入表單中,然後在地址中使用,而不是簡單地確保地址有效,因此轉到此處尋求幫助。 感謝

回答

3

您應該使用filter module

$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT); 
if ($id === false) { 
    // not an integer 
} 

或者您可以使用ctype_digit()檢查,如果一個變量僅由十進制數字:

if (ctype_digit($_GET['id'])) { 
    // it's an integer 
} else { 
    // not an integer 
} 

或更短:

ctype_digit($_GET['id']) or die("oops that's not an integer!"); 

dieexit會使您的代碼更少測試。


is_numeric將工作太,但它是一個數字,不僅整數的任何字符串表示返回true。

+0

這不會*檢查輸入是一個整數的有效表示。 –

+0

現在它會......掩蓋duff答案的方式。 – adlawson

+0

我已經改進了我的答案,謝謝 – arnaud576875

1

試試這個

<?php 
if (is_int($_GET["id"])) { 
echo "is integer\n"; 
} else { 
echo "is not an integer\n"; 
} 
?> 
+1

$ _GET「整數」實際上是字符串值。改用['is_numeric()'](http://php.net/manual/en/function.is-numeric.php)。 – adlawson

0

如果您已經排除了0爲您的整數ID有效數字,你可以簡單地做到以下幾點:

$id = (int) $_GET['id']; 
if (!$id) { 
    # no number -or- 0 given 
} else { 
    # regardless what have been given, it has been converted at least to some integer. 
} 

這是鑄造。現在$id始終是一個整數,因此使用更安全。

然而,大多數時候你需要檢查以及該號碼非負:

$id = max(0, $_GET['id']); 

max功能確實需要鑄造$_GET['id']成整數的照顧。如果提供的值大於0,它確保id爲0或更高。如果它是0或更低,則0是最大數目。

然後,如果您需要實際驗證輸入更嚴格,你可以把它放回一個字符串比較的原因:

if ("$id" === $_GET['id']) 
{ 
    # Input was done as a string representation of the integer value. 
}