Input validation with filter functions
Introduction
Although PHP has a lot of filter functions available, I found that still to many people are using (often incorrect) regular expressions to validate user input. The filter extension is simple, standard available and will fulfill the common validations. Below some pratical examples and things to consider when working with PHP filter functions.
Which are available?
Below a shameless copy paste of the PHP documentation.
- filter_has_var — Checks if variable of specified type exists
- filter_id — Returns the filter ID belonging to a named filter
- filter_input_array — Gets external variables and optionally filters them
- filter_input — Gets a specific external variable by name and optionally filters it
- filter_list — Returns a list of all supported filters
- filter_var_array — Gets multiple variables and optionally filters them
- filter_var — Filters a variable with a specified filter
Pratical use
Sanitizing
“Filter input escape output” every developer knows this but it is a repetitive job but with the filter extension filterering input became a lot easier. When you correctly filter input you drastically lower the change of application vulnerabilities.
Sanitizing a single variable
$sText = ' ';
$sText = filter_var($sText, FILTER_SANITIZE_STRING);
echo $sText; // This is a comment from a alert("scriptkiddie");
Sanitizing multiple variables, same principle as above but with an array, the filter will sanitize all values inside the array
filter_var_array($_POST, FILTER_SANITIZE_STRING);
Validating an email address
if(filter_var($sEmail, FILTER_VALIDATE_EMAIL) === false) {
$this->addError('Invalid email address', $sEmail);
}
Validation a complete array
Validating all your data at once with a single filter will make your code clear, all in one place and is more easy to maintain an example below.
$aData = array(
'student' => 'Sjoerd Maessen',
'class' => '21',
'grades' => array(
'math' => 9,
'geography' => 66,
'gymnastics' => 7.5
)
);
$aValidation = array(
'student' => FILTER_SANITIZE_STRING,
'class' => FILTER_VALIDATE_INT,
'grades' => array(
'filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_FORCE_ARRAY,
'options'=> array('min_range'=>0, 'max_range'=>10))
);
echo '';
var_dump(filter_var_array($aData, $aValidation));
/*array(3) {
["student"]=>
string(14) "Sjoerd Maessen"
["class"]=>
int(21) // Thats strange, my string is converted
["grades"]=>
array(3) {
["math"]=>
int(9)
["geography"]=>
bool(false) // 66 is > 10
["gymnastics"]=>
bool(false) // 7.5 is not an int
}
}*/
Note: okay I did not expect that the string '21' would validate true against FILTER_VALIDATE_INT, after some more testing I also noticed that min_range and max_range only work with FILTER_VALIDATE_INT, when using floats or scalars the options are just ignored, so be aware!
The sanitizing examples above can be made easily more restrictive by adding flags like FILTER_FLAG_STRIP_LOW to the sanitize filter, FILTER_FLAG_STRIP_LOW will for example strip all characters that have a numerical value below 32.
Things to consider
Although the filter functions are some time available some of them aren't flawless, at some points the documentation is missing or very unclear. Another example is the filter_var validation for IPv6 addresses. (see bug report #50117). So it is always a good thing to check if the filter is really doing what you expect it does. Write testcases before using. If you use it correctly you can write your validations in the blink of an eye, and this extension will be your new best friend.
Links
Filter functions
Filter flags
https://t.me/s/Beefcasino_rus/9
DealerShadow
28 Oct 25 at 1:36 pm
J’adore la vibe de Ruby Slots Casino, ca offre un plaisir vibrant. La selection est riche et diversifiee, comprenant des jeux crypto-friendly. Il propulse votre jeu des le debut. Disponible a toute heure via chat ou email. Les paiements sont surs et efficaces, par ailleurs des recompenses supplementaires seraient parfaites. En bref, Ruby Slots Casino merite un detour palpitant. De surcroit l’interface est simple et engageante, apporte une touche d’excitation. Un avantage les options de paris sportifs variees, propose des privileges personnalises.
Trouver les dГ©tails|
toxickingen6zef
28 Oct 25 at 1:42 pm
J’ai une passion debordante pour Sugar Casino, ca invite a plonger dans le fun. Les options sont aussi vastes qu’un horizon, comprenant des jeux crypto-friendly. Le bonus de bienvenue est genereux. Le service d’assistance est au point. Les transactions sont d’une fiabilite absolue, parfois des bonus varies rendraient le tout plus fun. Pour conclure, Sugar Casino offre une aventure inoubliable. A mentionner la plateforme est visuellement dynamique, ce qui rend chaque moment plus vibrant. Un plus les options de paris sportifs variees, qui motive les joueurs.
Avancer|
vibeknightan1zef
28 Oct 25 at 1:45 pm
https://t.me/Beefcasino_rus/34
DealerShadow
28 Oct 25 at 1:50 pm
Kamagra sans ordonnance: kamagra oral jelly – Kamagra livraison rapide en France
RichardImmon
28 Oct 25 at 2:00 pm
https://t.me/Official_mellstroy_casino/15
Calvindreli
28 Oct 25 at 2:02 pm
kraken сайт Kraken ссылка – это ключ к заветной двери, ведущей в глубины цифрового пространства, где правят свои законы. Убедитесь в подлинности источника, прежде чем доверить ему свои данные, ведь мошенники не дремлют. Остерегайтесь фишинговых сайтов и поддельных зеркал, чтобы ваше путешествие не обернулось разочарованием. Будьте бдительны и осмотрительны, и тогда сможете избежать неприятностей и насладиться всеми преимуществами платформы.
Kevinmoots
28 Oct 25 at 2:05 pm
https://t.me/Official_mellstroy_casino/8
Calvindreli
28 Oct 25 at 2:05 pm
https://t.me/Official_mellstroy_casino/12
Calvindreli
28 Oct 25 at 2:50 pm
https://t.me/s/Official_mellstroy_casino/59
Calvindreli
28 Oct 25 at 3:21 pm
https://t.me/s/Official_mellstroy_casino/21
Calvindreli
28 Oct 25 at 3:23 pm
https://t.me/s/Beefcasino_rus/17
AllInAce
28 Oct 25 at 3:28 pm
https://t.me/Official_mellstroy_casino/13
Calvindreli
28 Oct 25 at 3:28 pm
https://t.me/Official_mellstroy_casino/39
Calvindreli
28 Oct 25 at 4:01 pm
https://t.me/Official_mellstroy_casino/24
Calvindreli
28 Oct 25 at 4:32 pm
https://t.me/s/Official_mellstroy_casino/42
Calvindreli
28 Oct 25 at 4:36 pm
https://t.me/s/Official_mellstroy_casino/13
Calvindreli
28 Oct 25 at 5:08 pm
https://t.me/s/Official_mellstroy_casino/10
Calvindreli
28 Oct 25 at 5:40 pm
https://t.me/Official_mellstroy_casino/47
Calvindreli
28 Oct 25 at 5:42 pm
https://t.me/s/Official_mellstroy_casino/49
Calvindreli
28 Oct 25 at 5:47 pm
Промокод Melbet – это набор случайных или подобранных символов, которые позволяют новому игроку принять участие в акциях и получить подарки от БК Мелбет. К примеру, в 2026 году Мелбет промокод предлагает бонус 50 000 рублей на счет при регистрации. При выборе букмекерской конторы пользователи обращают внимание не только на маржу или коэффициенты, но и обязательно оценивают текущие акции. Крупные операторы предлагают бонусы на первый депозит, программу лояльности, фрибеты и другие виды поощрений. Бонусный код является самым распространённым видом привлечения клиентов в популярных букмекерских конторах. Чаще всего промокод Melbet представляет собой рандомный порядок букв и цифр, которые вводят в специальное поле в форме регистрации на сайте. Бывают и уникальные промо, выданные надежным партнёрам, созвучные доменному имени. промокод мелбет на сегодня позволяет получить повышенный бонус на первый депозит в размере 100% и бесплатную ставку на 400 RUB или фрибет на $30.
Georgeduh
28 Oct 25 at 6:20 pm
https://t.me/Official_mellstroy_casino/49
Calvindreli
28 Oct 25 at 6:25 pm