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

6,846 responses to “Input validation with filter functions”

  1. OLaneDrync Avatar
    OLaneDrync

    Howdy very cool blog!! Guy .. Beautiful .. Wonderful .. I’ll bookmark your web site and take the feeds additionally? I’m satisfied to find so many helpful information right here within the publish, we need develop extra techniques in this regard, thanks for sharing. . . . . .
    https://insgate.ru/

  2. Henryaloth Avatar
    Henryaloth

    http://mensrxindex.com/# online ed medicine

  3. Williamchabe Avatar
    Williamchabe

    pet prescriptions online: Vet Rx Index – pet drugs online

  4. RobertFup Avatar
    RobertFup

    Mens RX Index Mens RX Index ed online treatment

  5. AndrewMuh Avatar
    AndrewMuh

    online pet pharmacy: Vet Rx Index – pet pharmacy online

  6. Robertsmuch Avatar

    бездепозитные бонусы в казино казахстан В мире азартных онлайн-пространств бездепозитные бонусы сияют подобно маякам, зазывая искателей острых ощущений на неизведанные берега. Эти щедрые жесты казино, не требующие от игрока пополнения счета, дарят уникальную возможность — ощутить вкус игры, не рискуя собственными средствами. Они являются ключом, отпирающим массивные врата в царство слотов, рулетки и карточных столов, предлагая гостю испытать изысканность интерфейса, мощь софта и саму атмосферу заведения.

  7. Henryaloth Avatar
    Henryaloth
  8. AndrewMuh Avatar
    AndrewMuh

    vet pharmacy: Vet Rx Index – pet rx

  9. TylerShets Avatar
    TylerShets

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

  10. Williamchabe Avatar
    Williamchabe

    pet prescriptions online: Vet Rx Index – canada pet meds

  11. Frankendat Avatar

    документы входящие в проект производства работ Разработка ППР является обязательным этапом перед началом большинства строительных процессов, будь то капитальный ремонт, возведение нового объекта, монтаж оборудования или проведение специфических работ, таких как бетонирование, свайные работы или бурение.

  12. Williamchabe Avatar
    Williamchabe

    Certified Canada Rx: canadian pharmacies that deliver to the us – canadian drugs pharmacy

  13. AnthonyBop Avatar

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

  14. RobertFup Avatar
    RobertFup

    Mens RX Index where can i get ed pills buy erectile dysfunction pills

  15. AndrewMuh Avatar
    AndrewMuh

    ed drugs online: erection pills online – Mens RX Index

  16. Michaelimimb Avatar

    накрутка лайков в вк регистрация Чтобы добиться реального успеха, важно сочетать эти методы с качественным контентом и системным подходом, особенно при продвижении бизнеса, анализируя кейсы и применяя эффективные инструменты SMM.

  17. TylerShets Avatar
    TylerShets
  18. AndrewMuh Avatar
    AndrewMuh

    pet meds for dogs: Vet Rx Index – pet meds for dogs

  19. Henryaloth Avatar
    Henryaloth

    http://certifiedcanadarx.com/# reputable canadian online pharmacies

  20. Henryaloth Avatar
    Henryaloth
  21. MichaelHes Avatar

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

  22. Buddybriep Avatar

    кредит под залог квартиры Банки и кредитные организации рассматривают различные виды залога, предлагая индивидуальные условия для каждого клиента.

  23. TylerShets Avatar
    TylerShets

    https://mensrxindex.com/# order ed pills online

  24. TylerShets Avatar
    TylerShets

    https://petmedsmonitor.com/# online pet pharmacy

  25. Williamchabe Avatar
    Williamchabe

    pet meds for dogs: Vet Rx Index – online vet pharmacy

  26. RobertFup Avatar
    RobertFup

    best canadian pharmacy 77 canadian pharmacy Certified Canada Rx

  27. Henryaloth Avatar
    Henryaloth

    https://certifiedcanadarx.com/# reputable canadian pharmacy

  28. AndrewMuh Avatar
    AndrewMuh

    Certified Canada Rx: www canadianonlinepharmacy – Certified Canada Rx

  29. AndrewMuh Avatar
    AndrewMuh

    cheap erectile dysfunction pills: low cost ed meds – cheap ed meds

  30. TylerShets Avatar
    TylerShets
  31. Williamchabe Avatar
    Williamchabe

    pet drugs online: dog medication online – dog medicine

  32. RobertFup Avatar
    RobertFup

    reliable canadian pharmacy reviews Certified Canada Rx canadian pharmacy scam

  33. TylerShets Avatar
    TylerShets

    https://petmedsmonitor.com/# dog prescriptions online

  34. Williamchabe Avatar
    Williamchabe

    cheap ed medicine: online ed meds – generic ed meds online

  35. TylerShets Avatar
    TylerShets

    https://certifiedcanadarx.com/# canadian pharmacy world

  36. Thomasusamn Avatar
    Thomasusamn

    Промокод в букмекера — представляет собой уникальное сочетание букв и цифр, с помощью которого можно получить дополнительные привилегии от букмекера: фрибеты, возврат средств а также дополнительные бонусы. Букмекерские промокоды — это бонусные коды, которые вводятся при создании аккаунта а также в профиле пользователя. По ним можно получить freebet, стартовый бонус или страховку пари. Тут представлены самые актуальные промо-предложения в списке http://www.madguy.ru/images/pgs/1xbet_promokod_pri_registracii_bonus_5.html тут наличие новых кодов и обновление списков сразу после выхода новых акций.

  37. AndrewMuh Avatar
    AndrewMuh

    Mens RX Index: Mens RX Index – low cost ed medication

  38. AndrewMuh Avatar
    AndrewMuh

    dog prescriptions online: online vet pharmacy – discount pet meds

  39. Williamchabe Avatar
    Williamchabe

    buy erectile dysfunction pills online: online ed medications – Mens RX Index

  40. TylerShets Avatar
    TylerShets

    http://petmedsmonitor.com/# online pet pharmacy

Leave a Reply

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