Sanitization usually comes before validation. What you set up does the opposite. It tries to validate and then sanitize but since it should not be receiving the appropriate type, it always falls in the error message.
One way to sanitize is by doing a cast of the type using intval()
or preceding (int)
.
$var = (int)$var;
or
$var = intval($var);
However, beware of using type casting for what you’re doing because in recent versions of PHP it might not work as expected. It is safer to replace characters using string manipulation functions to perform consistent sanitization. And remembering that the cast itself is already a sanitization for the case in question.
Example (PHP5.6.19):
// http://localhost/tmp.php?n=a
echo (int)$_GET['n'];
This above test returns ZERO integer. It is an unexpected result because the received value does not contain any number.
A more consistent way is by substituting non-numerical characters:
function numbers_only($str, $exception = '')
{
return preg_replace('#[^0-9'.$exception.']#', '', mb_convert_kana($str, 'n'));
}
// http://localhost/tmp.php?n=a
echo '<br>numbers_only(): '.numbers_only($_GET['n']);
In this example, since there are no numbers, it returns empty because sanitization removed everything that was not recognized as numerical character.
Note that it also auto converts zenkaku characters, allowing zenkaku numbers to be sanitized to the ASCII standard with the function mb_convert_kana().
Adapting to your case would look something like this
// Checking if parameter exists
$n = isset($_GET['dep'])? $_GET['dep']: null;
// Checking if the parameter is not empty or equals to ZERO
if (!empty($n) || $n == '0') {
// Sanitization
$n = numbers_only($n);
// Check again if not empty and different of ZERO
if (empty($n) && $n != '0') {
$err = 'parameter do not contains numbers';
}
} else {
$err = 'parameter cannot be empty';
}
if (empty($err)) {
echo 'number: '.$n;
} else {
echo 'error: '.$err;
}
In the example above it is accepted the value 0 (ZERO). If you want to remove the zero, remove it from the conditional || $n == '0')
and && $n != '0'
.
products is quantity or monetary value?
– rray
Hello @rray, it’s department and sub-department values, I don’t know if this answers your question.
– adventistapr