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

514 responses to “Input validation with filter functions”

  1. sonictigeran3zef Avatar
    sonictigeran3zef

    J’adore le dynamisme de Betway Casino, on ressent une ambiance de fete. La bibliotheque est pleine de surprises, proposant des jeux de table sophistiques. Le bonus d’inscription est attrayant. Le suivi est impeccable. Les paiements sont surs et fluides, toutefois des recompenses supplementaires dynamiseraient le tout. En conclusion, Betway Casino offre une experience hors du commun. En complement la plateforme est visuellement dynamique, ce qui rend chaque partie plus fun. Egalement excellent les tournois frequents pour l’adrenaline, propose des avantages sur mesure.
    Lire les dГ©tails|

  2. TerryBoita Avatar

    бездепозитные бонусы казино без пополнения Бездепозитные бонусы за регистрацию с возможностью вывода – это отличный шанс начать играть в онлайн-казино без финансовых вложений и с реальным шансом на выигрыш. Главное – внимательно читайте условия каждой акции, чтобы понимать все правила и требования. Удачи в игре!

  3. JasonNergo Avatar
    JasonNergo

    Snabb leverans apoteksvaror online: apotek online sverige – Köp medicin utan recept Sverige

  4. UrbanByteok3zef Avatar
    UrbanByteok3zef

    Je suis enthousiaste a propos de Gamdom Casino, c’est un lieu ou l’adrenaline coule a flots. Les jeux proposes sont d’une diversite folle, comprenant des titres adaptes aux cryptomonnaies. Il offre un demarrage en fanfare. Le suivi est toujours au top. Le processus est transparent et rapide, bien que quelques spins gratuits en plus seraient top. En fin de compte, Gamdom Casino est un incontournable pour les joueurs. En bonus le design est moderne et energique, booste l’excitation du jeu. Egalement top les evenements communautaires engageants, garantit des paiements securises.
    Plongez-y|

  5. Solarpulseus8zef Avatar
    Solarpulseus8zef

    J’ai un faible pour Betify Casino, ca invite a l’aventure. Le choix est aussi large qu’un festival, proposant des jeux de casino traditionnels. Avec des depots instantanes. Le suivi est impeccable. Le processus est fluide et intuitif, de temps en temps plus de promotions frequentes boosteraient l’experience. En resume, Betify Casino est un must pour les passionnes. En bonus l’interface est lisse et agreable, facilite une immersion totale. Un point cle les evenements communautaires vibrants, cree une communaute soudee.
    Commencer maintenant|

  6. urbankingus3zef Avatar
    urbankingus3zef

    J’adore l’ambiance electrisante de Gamdom Casino, on ressent une ambiance de fete. La bibliotheque est pleine de surprises, incluant des paris sportifs en direct. Il offre un coup de pouce allechant. Disponible a toute heure via chat ou email. Les retraits sont simples et rapides, de temps en temps des recompenses supplementaires seraient parfaites. En fin de compte, Gamdom Casino est un immanquable pour les amateurs. A noter le design est tendance et accrocheur, permet une plongee totale dans le jeu. Particulierement interessant les evenements communautaires engageants, qui dynamise l’engagement.
    Visiter aujourd’hui|

  7. betacodeer3zef Avatar
    betacodeer3zef

    J’adore l’ambiance electrisante de Betify Casino, ca transporte dans un monde d’excitation. Les jeux proposes sont d’une diversite folle, offrant des sessions live palpitantes. Il offre un coup de pouce allechant. Le service d’assistance est au point. Le processus est simple et transparent, neanmoins des bonus diversifies seraient un atout. Dans l’ensemble, Betify Casino offre une experience hors du commun. Par ailleurs l’interface est intuitive et fluide, apporte une touche d’excitation. Particulierement fun le programme VIP avec des avantages uniques, renforce la communaute.
    Lire la suite|

  8. GeorgeAlila Avatar
    GeorgeAlila

    https://kortingapotheek.xyz/# online apotheek nederland

  9. JosephCit Avatar
    JosephCit

    http://tryggapotekguiden.com/# Snabb leverans apoteksvaror online

  10. GeorgeAlila Avatar
    GeorgeAlila

    https://tryggapotekguiden.com/# Bästa nätapotek 2025

  11. Williamseelo Avatar
    Williamseelo

    mexican pharmacy: Mexican pharmacies ranked 2025 – buy medications from Mexico legally

  12. StephenLib Avatar
    StephenLib

    Kundevurderinger av nettapotek Apotek på nett sammenligning Hvilket apotek på nett er best i Norge

Leave a Reply

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