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

10,290 responses to “Input validation with filter functions”

  1. Michaelves Avatar
    Michaelves

    Paw Trust Meds: Paw Trust Meds – Paw Trust Meds

  2. RichardUtize Avatar
    RichardUtize

    Официальная ссылка маркетплейса “Зелёный Мир”

    Зелёный_Мир

  3. ArthurLap Avatar
    ArthurLap

    canada cloud pharmacy: real canadian pharmacy – legit canadian pharmacy online

  4. AndrewHoozy Avatar
    AndrewHoozy

    Global India Pharmacy: Global India Pharmacy – Global India Pharmacy

  5. Michaelves Avatar
    Michaelves

    indian pharmacy paypal: india online pharmacy – Global India Pharmacy

  6. AndrewHoozy Avatar
    AndrewHoozy

    discount pet meds: Paw Trust Meds – Paw Trust Meds

  7. ArthurLap Avatar
    ArthurLap

    best rated canadian pharmacy: canadian drugs – canadian pharmacy 1 internet online drugstore

  8. Gabrielnes Avatar
    Gabrielnes
  9. Gabrielnes Avatar
    Gabrielnes

    https://globalindiapharmacy.shop/# Global India Pharmacy

  10. WilliamSip Avatar
    WilliamSip
  11. Gabrielnes Avatar
    Gabrielnes

    https://pawtrustmeds.shop/# п»їdog medication online

  12. ArthurLap Avatar
    ArthurLap

    vet pharmacy: Paw Trust Meds – Paw Trust Meds

  13. EarnestAbent Avatar
    EarnestAbent

    What’s up every one, here every one is sharing these kinds of know-how, therefore it’s nice to read this weblog, and I used to pay a visit this web site every day.
    Betify Casino

  14. RichardUtize Avatar
    RichardUtize

    Официальная ссылка маркетплейса “Зелёный Мир”

    zmir

  15. AndrewHoozy Avatar
    AndrewHoozy

    legitimate canadian online pharmacies: medication canadian pharmacy – my canadian pharmacy review

  16. Michaelves Avatar
    Michaelves

    pet drugs online: Paw Trust Meds – Paw Trust Meds

  17. WilliamSip Avatar
    WilliamSip

    http://pawtrustmeds.com/# pet drugs online

  18. Michaelves Avatar
    Michaelves

    canada pet meds: п»їdog medication online – Paw Trust Meds

  19. RichardUtize Avatar
    RichardUtize

    Официальная ссылка маркетплейса “Зелёный Мир”

    вход зеленый мир

  20. AndrewHoozy Avatar
    AndrewHoozy

    canadian pharmacy world reviews: NorthAccess Rx – safe canadian pharmacies

  21. AndrewHoozy Avatar
    AndrewHoozy

    best india pharmacy: Global India Pharmacy – Global India Pharmacy

  22. Michaelves Avatar
    Michaelves

    indian pharmacies safe: online shopping pharmacy india – Online medicine home delivery

  23. Danieljew Avatar

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

  24. Gabrielnes Avatar
    Gabrielnes
  25. Gabrielnes Avatar
    Gabrielnes

    http://northaccessrx.com/# canadian pharmacy 24h com

  26. JoshuaJat Avatar
    JoshuaJat

    Знакомства ДНР ТГ Наш сервис создан специально для вас, предлагая удобную платформу для поиска серьезных отношений и приятного общения. Откройте для себя новый уровень онлайн-общения. Наши возможности простираются на всю территорию ЛНР, предлагая аналогичные сервисы для поиска.

  27. Enriquesweds Avatar

    Пакеты с бегунком Эти пакеты идеально подходят для хранения различных предметов, от мелких аксессуаров до продуктов питания, обеспечивая надежную защиту от влаги и пыли.

  28. Gabrielnes Avatar
    Gabrielnes

    http://globalindiapharmacy.com/# world pharmacy india

  29. WilliamSip Avatar
    WilliamSip
  30. AndrewHoozy Avatar
    AndrewHoozy

    dog medicine: Paw Trust Meds – Paw Trust Meds

  31. RichardUtize Avatar
    RichardUtize

    Официальная ссылка маркетплейса “Зелёный Мир”

    zmir

  32. ArthurLap Avatar
    ArthurLap

    best pet rx: Paw Trust Meds – Paw Trust Meds

  33. JoshuaJat Avatar
    JoshuaJat

    найти девушку ДНР Знакомства Донецк ТГ — это быстрый и эффективный способ найти девушку в вашем городе для серьезных отношений или дружбы. Найти девушку в ЛНР стало проще, чем когда-либо, благодаря удобному интерфейсу и активному сообществу.

  34. Michaelves Avatar
    Michaelves

    Paw Trust Meds: Paw Trust Meds – Paw Trust Meds

  35. Robertanomy Avatar
    Robertanomy

    p179d85 ошибка mercedes p179d00 ошибка

  36. ArthurLap Avatar
    ArthurLap

    canadian pharmacy king: NorthAccess Rx – canadian pharmacy service

Leave a Reply

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