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

Comments

495 responses to “Input validation with filter functions”

  1. Johnnyfuede Avatar
    Johnnyfuede

    Safe Meds Guide: online pharmacy – trusted online pharmacy USA

  2. Edmundexpon Avatar
    Edmundexpon

    best Irish pharmacy websites

  3. HaroldSHems Avatar
    HaroldSHems

    online pharmacy: Uk Meds Guide – non-prescription medicines UK

  4. Haroldovaph Avatar
    Haroldovaph

    http://irishpharmafinder.com/# discount pharmacies in Ireland

  5. Edmundexpon Avatar
    Edmundexpon

    pharmacy delivery Ireland

  6. HaroldSHems Avatar
    HaroldSHems

    Safe Meds Guide: SafeMedsGuide – Safe Meds Guide

  7. Hermanengam Avatar
    Hermanengam

    UK online pharmacies list cheap medicines online UK affordable medications UK

  8. Johnnyfuede Avatar
    Johnnyfuede

    pharmacy online: AussieMedsHubAu – verified online chemists in Australia

  9. Hermanengam Avatar
    Hermanengam

    online pharmacy online pharmacy Uk Meds Guide

  10. JerrySussy Avatar

    Betwinner Kenya registration is quick and secure via https://bet-promo-codes.com/sportsbook-reviews/betwinner-registration/ — suitable for both desktop and mobile users.

  11. Johnnyfuede Avatar
    Johnnyfuede

    Irish online pharmacy reviews: affordable medication Ireland – online pharmacy

  12. echosparkan9zef Avatar
    echosparkan9zef

    J’ai une affection particuliere pour Frumzi Casino, on ressent une ambiance de fete. Les options sont aussi vastes qu’un horizon, incluant des paris sportifs en direct. 100% jusqu’a 500 € + tours gratuits. Le support est pro et accueillant. Le processus est fluide et intuitif, neanmoins des offres plus genereuses rendraient l’experience meilleure. En bref, Frumzi Casino assure un divertissement non-stop. Pour completer la navigation est claire et rapide, ce qui rend chaque session plus excitante. Un atout les nombreuses options de paris sportifs, propose des privileges personnalises.
    Jeter un coup d’œil|

  13. Sonicqueenus1zef Avatar
    Sonicqueenus1zef

    J’adore la vibe de Frumzi Casino, ca offre un plaisir vibrant. La bibliotheque de jeux est captivante, comprenant des titres adaptes aux cryptomonnaies. Le bonus initial est super. Le suivi est d’une fiabilite exemplaire. Les paiements sont securises et rapides, cependant des recompenses supplementaires dynamiseraient le tout. Pour conclure, Frumzi Casino offre une aventure memorable. Pour ajouter la navigation est claire et rapide, ce qui rend chaque moment plus vibrant. Egalement genial les options variees pour les paris sportifs, renforce la communaute.
    Voir le site|

  14. cybercodeon9zef Avatar
    cybercodeon9zef

    Je suis completement seduit par Cheri Casino, ca transporte dans un univers de plaisirs. La bibliotheque est pleine de surprises, proposant des jeux de cartes elegants. Il amplifie le plaisir des l’entree. Le support est rapide et professionnel. Les gains sont transferes rapidement, parfois des bonus plus frequents seraient un hit. En resume, Cheri Casino vaut une exploration vibrante. De surcroit la plateforme est visuellement vibrante, amplifie le plaisir de jouer. Un avantage notable les tournois reguliers pour la competition, assure des transactions fiables.
    Commencer Г  lire|

  15. FrostWingin2zef Avatar
    FrostWingin2zef

    J’ai un veritable coup de c?ur pour Wild Robin Casino, il offre une experience dynamique. Les titres proposes sont d’une richesse folle, avec des slots aux designs captivants. Il rend le debut de l’aventure palpitant. Les agents sont rapides et pros. Les transactions sont toujours fiables, mais des bonus plus varies seraient un plus. Pour faire court, Wild Robin Casino offre une aventure memorable. A mentionner le design est style et moderne, apporte une touche d’excitation. A noter les options de paris sportifs variees, qui dynamise l’engagement.
    Consulter les dГ©tails|

  16. HaroldSHems Avatar
    HaroldSHems

    verified online chemists in Australia: best Australian pharmacies – pharmacy online

  17. Edmundexpon Avatar
    Edmundexpon

    buy medicine online legally Ireland

  18. Shadoweagleos9zef Avatar
    Shadoweagleos9zef

    Je suis bluffe par Instant Casino, ca invite a plonger dans le fun. Il y a une abondance de jeux excitants, proposant des jeux de casino traditionnels. Il amplifie le plaisir des l’entree. Le suivi est impeccable. Les transactions sont d’une fiabilite absolue, de temps a autre quelques tours gratuits supplementaires seraient cool. En somme, Instant Casino est une plateforme qui fait vibrer. Ajoutons que la plateforme est visuellement dynamique, donne envie de prolonger l’aventure. A noter le programme VIP avec des privileges speciaux, assure des transactions fluides.
    Entrer maintenant|

  19. AlphaMindos7zef Avatar
    AlphaMindos7zef

    Je suis completement seduit par Cheri Casino, on ressent une ambiance de fete. Les titres proposes sont d’une richesse folle, avec des machines a sous aux themes varies. Avec des depots instantanes. Le service est disponible 24/7. Les transactions sont fiables et efficaces, quelquefois plus de promos regulieres dynamiseraient le jeu. En somme, Cheri Casino vaut une visite excitante. Pour ajouter la navigation est intuitive et lisse, permet une immersion complete. Particulierement cool les tournois frequents pour l’adrenaline, propose des avantages uniques.
    Cliquer pour voir|

  20. WildEdgeax3zef Avatar
    WildEdgeax3zef

    Je suis bluffe par Frumzi Casino, il cree un monde de sensations fortes. Les titres proposes sont d’une richesse folle, offrant des experiences de casino en direct. Le bonus de bienvenue est genereux. Disponible 24/7 pour toute question. Les retraits sont lisses comme jamais, bien que des recompenses additionnelles seraient ideales. En resume, Frumzi Casino est un choix parfait pour les joueurs. D’ailleurs la plateforme est visuellement vibrante, incite a prolonger le plaisir. Un plus les paiements securises en crypto, offre des recompenses regulieres.
    Commencer Г  explorer|

  21. Cityfirear2zef Avatar
    Cityfirear2zef

    Je suis accro a Instant Casino, ca pulse comme une soiree animee. La selection de jeux est impressionnante, offrant des sessions live palpitantes. 100% jusqu’a 500 € avec des spins gratuits. Le service client est de qualite. Les paiements sont surs et efficaces, cependant quelques free spins en plus seraient bienvenus. En fin de compte, Instant Casino est un lieu de fun absolu. Par ailleurs l’interface est intuitive et fluide, booste l’excitation du jeu. Un point cle les competitions regulieres pour plus de fun, offre des recompenses regulieres.
    Visiter la page web|

  22. HaroldSHems Avatar
    HaroldSHems

    trusted online pharmacy USA: online pharmacy reviews and ratings – promo codes for online drugstores

  23. Edmundexpon Avatar
    Edmundexpon

    affordable medication Ireland

  24. Hermanengam Avatar
    Hermanengam

    best pharmacy sites with discounts best pharmacy sites with discounts best pharmacy sites with discounts

  25. Johnnyfuede Avatar
    Johnnyfuede

    pharmacy delivery Ireland: affordable medication Ireland – online pharmacy

  26. Hermanengam Avatar
    Hermanengam

    online pharmacy promo codes for online drugstores online pharmacy

  27. Haroldovaph Avatar
    Haroldovaph

    https://safemedsguide.shop/# best online pharmacy

  28. Johnnyfuede Avatar
    Johnnyfuede

    Irish online pharmacy reviews: Irish Pharma Finder – discount pharmacies in Ireland

  29. HaroldSHems Avatar
    HaroldSHems

    best Irish pharmacy websites: best Irish pharmacy websites – buy medicine online legally Ireland

  30. Edmundexpon Avatar
    Edmundexpon

    irishpharmafinder

  31. HaroldSHems Avatar
    HaroldSHems

    best UK pharmacy websites: online pharmacy – UkMedsGuide

  32. Edmundexpon Avatar
    Edmundexpon

    top-rated pharmacies in Ireland

  33. Haroldovaph Avatar
    Haroldovaph

    https://aussiemedshubau.shop/# verified online chemists in Australia

  34. Hermanengam Avatar
    Hermanengam

    online pharmacy australia Aussie Meds Hub Australia Australian pharmacy reviews

  35. Johnnyfuede Avatar
    Johnnyfuede

    online pharmacy reviews and ratings: cheapest pharmacies in the USA – trusted online pharmacy USA

  36. Hermanengam Avatar
    Hermanengam

    UkMedsGuide trusted online pharmacy UK Uk Meds Guide

  37. Johnnyfuede Avatar
    Johnnyfuede

    best UK pharmacy websites: legitimate pharmacy sites UK – UK online pharmacies list

Leave a Reply

Your email address will not be published. Required fields are marked *