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

8,289 responses to “Input validation with filter functions”

  1. ThomasRUM Avatar
    ThomasRUM

    MedBridge Pharmacy: www canadianonlinepharmacy – MedBridge Pharmacy

  2. Patrickvew Avatar
    Patrickvew

    canadian online pharmacy viagra: MedBridge Pharmacy – canadian pharmacy cheap

  3. ThomasRUM Avatar
    ThomasRUM

    top 10 online pharmacy in india: online pharmacy india – online pharmacy india

  4. Darrenplors Avatar
    Darrenplors

    canadian compounding pharmacy MedBridge Pharmacy canadianpharmacy com

  5. Brianbeate Avatar
    Brianbeate

    https://trustrxindia.shop/# buy medicines online in india

  6. Darrenplors Avatar
    Darrenplors

    best online pharmacy india TrustRx India top online pharmacy india

  7. Patrickvew Avatar
    Patrickvew

    indian pharmacy: TrustRx India – Online medicine home delivery

  8. AnthonyTap Avatar
    AnthonyTap

    https://medbridgepharmacy.com/# safe canadian pharmacy

  9. Stevenabada Avatar

    1хбет промокоды на сегодня Вводите действующий купон на https://chernovorot.ru/wp-content/plugins/?1xbet_promokod_pri_registracii_bonus_segodnya.html и получите бонус 100% на депозит, чтобы получить стартовый капитал для игры.

  10. Patrickvew Avatar
    Patrickvew

    viagra from canadian pharmacy: pharmaceutical online – hq pharmacy online 365

  11. ThomasRUM Avatar
    ThomasRUM

    MedBridge Pharmacy: MedBridge Pharmacy – canadian pharmacy phone number

  12. Darrenplors Avatar
    Darrenplors

    best india pharmacy indianpharmacy com buy medicines online in india

  13. ThomasRUM Avatar
    ThomasRUM

    MedicoBridge RX: buying prescription drugs in mexico – mexican online pharmacies

  14. ThomasRUM Avatar
    ThomasRUM

    online mexican pharmacies: mexican pharmacies that ship to us – mexican pharmacies online

  15. Patrickvew Avatar
    Patrickvew

    MedicoBridge RX: tijuana pharmacy online – mexico medicine

  16. Brianbeate Avatar
    Brianbeate

    https://trustrxindia.com/# indian pharmacies safe

  17. AnthonyTap Avatar
    AnthonyTap
  18. Brianbeate Avatar
    Brianbeate

    https://trustrxindia.com/# online pharmacy india

  19. AnthonyTap Avatar
    AnthonyTap

    https://trustrxindia.com/# reputable indian online pharmacy

  20. Patrickvew Avatar
    Patrickvew

    top 10 online pharmacy in india: pharmacy no prescription required – legal canadian pharmacy online

  21. Brianbeate Avatar
    Brianbeate
  22. ThomasRUM Avatar
    ThomasRUM

    MedicoBridge RX: MedicoBridge RX – mexico pharmacy list

  23. ThomasRUM Avatar
    ThomasRUM

    best canadian pharmacy to buy from: canadian pharmacy ratings – canadianpharmacymeds

  24. Darrenplors Avatar
    Darrenplors

    online pharmacy mexico mexican pharmacy prices MedicoBridge RX

  25. ThomasRUM Avatar
    ThomasRUM

    MedBridge Pharmacy: rxpharmacycoupons – big pharmacy online

  26. Darrenplors Avatar
    Darrenplors

    maple leaf pharmacy in canada canadian pharmacy no prescription MedBridge Pharmacy

  27. Patrickvew Avatar
    Patrickvew

    MedBridge Pharmacy: reputable canadian pharmacy – cheapest pharmacy for prescription drugs

  28. Patrickvew Avatar
    Patrickvew

    MedicoBridge RX: mexican farmacia – mexican pharmacy near me

  29. Darrenplors Avatar
    Darrenplors

    MedBridge Pharmacy MedBridge Pharmacy MedBridge Pharmacy

  30. Cliftonmok Avatar

    mafia casino Bienvenue sur Mafia Casino, le domaine des jeux d’argent en ligne. Decouvrez notre avis detaille, le processus de connexion securise et des bonus exclusifs. Site officiel 2026.

  31. ThomasRUM Avatar
    ThomasRUM

    Online medicine home delivery: buy medicines online in india – indian pharmacy paypal

  32. Brianbeate Avatar
    Brianbeate

    https://trustrxindia.com/# indian pharmacy online

  33. ThomasRUM Avatar
    ThomasRUM

    canadian pharmacy king: MedBridge Pharmacy – MedBridge Pharmacy

  34. Patrickvew Avatar
    Patrickvew

    MedicoBridge RX: farmacia pharmacy mexico – MedicoBridge RX

  35. AnthonyTap Avatar
    AnthonyTap
  36. ThomasRUM Avatar
    ThomasRUM

    india online pharmacy: TrustRx India – Online medicine order

  37. Brianbeate Avatar
    Brianbeate

    https://trustrxindia.shop/# india online pharmacy

  38. JamesAlord Avatar
    JamesAlord

    двухъярусная кровать Создайте современную гостиную или уютную детскую комнату с нашей мебелью, которая идеально подойдет для детей любого возраста, включая стильные детские кроватки и двухъярусные кровати.

  39. Patrickvew Avatar
    Patrickvew

    pharmacy rx world canada: pharmacy orlando – reputable indian pharmacies

  40. Brianbeate Avatar
    Brianbeate

    https://trustrxindia.com/# Online medicine home delivery

  41. Patrickvew Avatar
    Patrickvew

    mexican pharmacys: medicine from mexico – pharmacy mexico

  42. RichardVok Avatar
    RichardVok

    Russia Телевизионные, онлайн и газетные форматы новостей, а также блоги и видеоконтент на платформах вроде Дзен и VK, предлагают разнообразные способы получения информации, от кратких сводок новостей часа до глубоких аналитических материалов.

  43. AnthonyTap Avatar
    AnthonyTap
  44. Darrenplors Avatar
    Darrenplors

    online mexican pharmacy pharmacy in mexico mexican pharmacy

  45. AnthonyTap Avatar
    AnthonyTap
  46. Darrenplors Avatar
    Darrenplors

    reputable indian pharmacies india pharmacy indian pharmacy online

  47. ThomasRUM Avatar
    ThomasRUM

    MedicoBridge RX: MedicoBridge RX – MedicoBridge RX

  48. ThomasRUM Avatar
    ThomasRUM

    pharmacies in mexico that ship to the us: mexican pharmacies online – online pharmacy in mexico

  49. BradleyJuite Avatar

    аренда ямобура Свяжитесь с нами, чтобы выбрать и заказать необходимую технику для ваших задач.

  50. ThomasRUM Avatar
    ThomasRUM

    pharma mexicana: MedicoBridge RX – MedicoBridge RX

Leave a Reply

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