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
Je suis accro a Wild Robin Casino, ca invite a l’aventure. Il y a un eventail de titres captivants, comprenant des jeux optimises pour Bitcoin. Il rend le debut de l’aventure palpitant. Le service client est excellent. Les transactions sont toujours securisees, de temps en temps des offres plus genereuses seraient top. En fin de compte, Wild Robin Casino vaut une visite excitante. A mentionner le design est moderne et attrayant, ajoute une touche de dynamisme. Un element fort les tournois reguliers pour s’amuser, cree une communaute soudee.
http://www.wildrobincasinomobilefr.com|
globalflowis1zef
2 Nov 25 at 4:24 pm
Je suis enthousiasme par Cheri Casino, il cree un monde de sensations fortes. La selection est riche et diversifiee, proposant des jeux de cartes elegants. Il donne un elan excitant. Les agents repondent avec rapidite. Les transactions sont fiables et efficaces, par moments plus de promotions frequentes boosteraient l’experience. En bref, Cheri Casino garantit un amusement continu. En plus le site est fluide et attractif, facilite une experience immersive. Particulierement attrayant les options variees pour les paris sportifs, qui motive les joueurs.
Aller à l’intérieur|
wildmindok4zef
2 Nov 25 at 4:33 pm
Je suis emerveille par Cheri Casino, ca offre un plaisir vibrant. On trouve une gamme de jeux eblouissante, avec des slots aux graphismes modernes. Avec des transactions rapides. Les agents sont toujours la pour aider. Les paiements sont surs et efficaces, a l’occasion des bonus varies rendraient le tout plus fun. Pour faire court, Cheri Casino offre une experience hors du commun. A signaler le design est moderne et attrayant, ajoute une touche de dynamisme. Egalement top les options de paris sportifs variees, qui motive les joueurs.
https://chericasinoappfr.com/|
CityLogicar8zef
2 Nov 25 at 4:38 pm
online pharmacy: online pharmacy – best Irish pharmacy websites
Johnnyfuede
2 Nov 25 at 4:45 pm
Je suis epate par Instant Casino, ca invite a plonger dans le fun. Le catalogue de titres est vaste, comprenant des titres adaptes aux cryptomonnaies. 100% jusqu’a 500 € avec des free spins. Le support client est irreprochable. Les transactions sont fiables et efficaces, de temps en temps des offres plus genereuses seraient top. En fin de compte, Instant Casino garantit un amusement continu. En bonus le design est moderne et energique, donne envie de continuer l’aventure. Un atout le programme VIP avec des avantages uniques, propose des privileges personnalises.
Apprendre les dГ©tails|
swiftpulseos5zef
2 Nov 25 at 4:55 pm
trusted online pharmacy Ireland
Edmundexpon
2 Nov 25 at 5:28 pm
https://t.me/s/UD_sOL
AlbertTeery
2 Nov 25 at 5:45 pm
https://t.me/s/ud_riObet
AlbertTeery
2 Nov 25 at 5:47 pm
https://t.me/s/uD_1xbeT
AlbertTeery
2 Nov 25 at 5:52 pm
https://t.me/s/official_1win_aviator/273
BluffMaster
2 Nov 25 at 6:25 pm
https://t.me/s/ud_keNT
AlbertTeery
2 Nov 25 at 6:25 pm
https://t.me/s/official_1win_aviator/188
LuckyBandit
2 Nov 25 at 6:34 pm
https://t.me/official_1win_aviator/192
AceSorcerer
2 Nov 25 at 6:54 pm
https://t.me/s/uD_Izzi
AlbertTeery
2 Nov 25 at 6:57 pm
affordable medication Ireland
Edmundexpon
2 Nov 25 at 6:57 pm
non-prescription medicines UK: UK online pharmacies list – cheap medicines online UK
HaroldSHems
2 Nov 25 at 6:58 pm
https://t.me/s/Ud_joYCASino
AlbertTeery
2 Nov 25 at 6:59 pm
https://t.me/s/ud_IRwiN
AlbertTeery
2 Nov 25 at 7:04 pm
legitimate pharmacy sites UK [url=http://ukmedsguide.com/#]best UK pharmacy websites[/url] legitimate pharmacy sites UK
Hermanengam
2 Nov 25 at 7:19 pm
https://t.me/s/official_1win_aviator/58
AllInAce
2 Nov 25 at 7:24 pm
Code promo pari gratuit 1xbet
AbrahamERAME
2 Nov 25 at 7:47 pm
самосвал Седельный: Оптимальное решение для междугородних перевозок. Устойчивость и безопасность на дороге. Комфорт для водителя в дальних рейсах.
Richardaquat
2 Nov 25 at 8:07 pm
https://t.me/s/UD_BOoi
AlbertTeery
2 Nov 25 at 8:10 pm
https://t.me/s/Ud_LEX
AlbertTeery
2 Nov 25 at 8:12 pm
https://t.me/s/ud_jeT
AlbertTeery
2 Nov 25 at 8:16 pm
non-prescription medicines UK: trusted online pharmacy UK – affordable medications UK
HaroldSHems
2 Nov 25 at 8:31 pm
affordable medication Ireland: top-rated pharmacies in Ireland – pharmacy delivery Ireland
Johnnyfuede
2 Nov 25 at 9:14 pm
https://t.me/s/UD_PInco
AlbertTeery
2 Nov 25 at 9:15 pm
affordable medications UK [url=http://ukmedsguide.com/#]cheap medicines online UK[/url] best UK pharmacy websites
Hermanengam
2 Nov 25 at 9:18 pm
https://t.me/s/UD_VODKA
AlbertTeery
2 Nov 25 at 9:52 pm
https://t.me/s/UD_pIn_uP
AlbertTeery
2 Nov 25 at 10:18 pm
https://t.me/s/ud_CAsiNo_X
AlbertTeery
2 Nov 25 at 10:24 pm
buy medications online safely: online pharmacy reviews and ratings – top rated online pharmacies
Johnnyfuede
2 Nov 25 at 10:33 pm
https://t.me/s/Ud_StarDa
AlbertTeery
2 Nov 25 at 10:54 pm
https://t.me/s/uD_LEgzO
AlbertTeery
2 Nov 25 at 11:20 pm
online pharmacy
Edmundexpon
2 Nov 25 at 11:23 pm
https://t.me/s/uD_StAkE
AlbertTeery
2 Nov 25 at 11:26 pm
https://t.me/s/UD_gGbET
AlbertTeery
2 Nov 25 at 11:56 pm
https://t.me/s/uD_KomEtA
AlbertTeery
3 Nov 25 at 12:22 am
https://t.me/s/UD_vULKAn
AlbertTeery
3 Nov 25 at 12:29 am
cheapest pharmacies in the USA: Safe Meds Guide – best online pharmacy
HaroldSHems
3 Nov 25 at 12:32 am
pharmacy delivery Ireland
Edmundexpon
3 Nov 25 at 12:51 am
best pharmacy sites with discounts [url=https://safemedsguide.com/#]top rated online pharmacies[/url] SafeMedsGuide
Hermanengam
3 Nov 25 at 1:14 am
https://t.me/s/ud_PLAYfortunA
AlbertTeery
3 Nov 25 at 1:24 am
http://irishpharmafinder.com/# best Irish pharmacy websites
Haroldovaph
3 Nov 25 at 1:36 am
https://t.me/s/UD_pokeRdOM
AlbertTeery
3 Nov 25 at 1:59 am
trusted online pharmacy Australia: Aussie Meds Hub – Australian pharmacy reviews
HaroldSHems
3 Nov 25 at 2:06 am
https://t.me/s/ud_lEon
AlbertTeery
3 Nov 25 at 2:26 am
https://t.me/s/ud_rox
AlbertTeery
3 Nov 25 at 2:28 am
https://t.me/s/UD_DriP
AlbertTeery
3 Nov 25 at 2:32 am