2013-11-04 18 views
0

我使用is_numeric驗證來自POST數據來像整數:

if(! is_numeric($_POST['integer_string'])) return FALSE // not a integer 

接着我發現如果該值有小數點is_numeric將返回TRUE。

下一個我試圖鑄造和is_int:

$int = (int) $_POST['numeric_string']; 
if(! $int) return FALSE // not a integer 

但非數值通過後鑄造將削減整數。

$int = '222i2'; 
echo $int; 
// 222 

我試圖驗證的整數將用於SQL中的WHERE子句以標識整數主鍵。

什麼是從POST數據驗證整數的傻瓜證明方式,或者您個人如何處理此問題?

+0

有很多騙局。我選擇了[php驗證整數](http://stackoverflow.com/questions/4100022/php-validate-integer),因爲它包含兩個正確的答案:正則表達式和'filter_input()'。 –

+0

['ctype_digit'](http://php.net/ctype_digit) – deceze

+0

我查看了很多其他答案,但沒有一個將整數指定爲主鍵。但我想這與其他整數沒有什麼不同。 –

回答

2

傻瓜證明的方式在PHP中使用驗證什麼是filter_var()filter_input()。當然,還可以使用PDOMySQLi準備好的語句。

爲了您的具體使用情況:

<?php 

$id = filter_input(
    INPUT_POST,   // Submitted via $_POST 
    "integer_string",  // Offset name in $_POST 
    FILTER_VALIDATE_INT, // The validation method 
    FILTER_REQUIRE_SCALAR // NULL and empty aren't valid 
); 

if ($id === false) { 
    throw new InvalidArgumentException("Not an int!"); 
} 

// Assuming you have a Database object that wraps your DB stuff. 
$database->query("SELECT * FROM `table` WHERE `id` = ? LIMIT 1", "d", [ $id ]); 

?> 

如果你的PHP版本不支持各種過濾功能執行以下操作:

<?php 

if (ctype_digit($_POST["integer_string"]) === false) { 
    throw new InvalidArgumentException; 
} 

// Before PHP 5.1.0 
if (empty($_POST["integer_string"]) || ctype_digit($_POST["integer_string"]) === false) { 
    throw new InvalidArgumentException; 
} 

?> 
+0

謝謝你,你給了一個非常翔實的答覆。 –

2

PHP有濾波器輸入

http://www.php.net/manual/en/function.filter-input.php

,你可以用FILTER_VALIDATE_INT

+0

'filter_input()'不是單元可測試的,但如果單元測試很重要,可以使用'filter_var()'。 – Fleshgrinder

+0

這就是我一直在尋找的,謝謝。單元測試不是一個問題因爲我只是不這樣做 –

0

爲PHP < 5.2,你可以使用正則表達式:

preg_match("/^[0-9]+$/", $_POST["integer_string"]); 

http://php.net/manual/en/function.preg-match.php

+0

永遠不要使用正則表達式進行類型驗證! – Fleshgrinder

+0

@Fleshgrinder - 爲什麼不呢? –

+0

爲作業使用正確的工具,這是該作業的錯誤工具。當然,正則表達式是正確的(我沒有說它不是)。另外,正則表達式在驗證代碼中有它們的用例,但僅用於驗證無法以其他方式驗證的內容。 – Fleshgrinder