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,845 responses to “Input validation with filter functions”

  1. Henryaloth Avatar
    Henryaloth

    http://certifiedcanadarx.com/# certified canadian pharmacy

  2. RonaldCrido Avatar

    Активировал приветственный бонус на Монро казино бонус — отыграл без сложностей, условия адекватные.

  3. RonaldCrido Avatar

    Вейджер на https://ethnofund.ru адекватный, реально отыграть.

  4. GeraldPaf Avatar

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

  5. AndrewMuh Avatar
    AndrewMuh

    best canadian pharmacy to buy from: northwest canadian pharmacy – canadian online pharmacy

  6. Williamchabe Avatar
    Williamchabe

    reputable canadian online pharmacy: canadian pharmacies that deliver to the us – best mail order pharmacy canada

  7. AndrewMuh Avatar
    AndrewMuh

    safe canadian pharmacy: cheap canadian pharmacy – Certified Canada Rx

  8. RobertFup Avatar
    RobertFup

    Mens RX Index Mens RX Index buying erectile dysfunction pills online

  9. Henryaloth Avatar
    Henryaloth

    https://certifiedcanadarx.com/# canadian drugs online

  10. TylerShets Avatar
    TylerShets

    http://mensrxindex.com/# low cost ed medication

  11. Williamchabe Avatar
    Williamchabe

    best canadian pharmacy online: Certified Canada Rx – drugs from canada

  12. Henryaloth Avatar
    Henryaloth

    https://mensrxindex.com/# how to get ed meds online

  13. Henryaloth Avatar
    Henryaloth

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

  14. EarnestAbent Avatar
    EarnestAbent

    Hello Dear, are you genuinely visiting this site regularly, if so afterward you will definitely obtain fastidious knowledge.
    официальный сайт leebet

  15. TylerShets Avatar
    TylerShets
  16. AndrewMuh Avatar
    AndrewMuh

    Certified Canada Rx: online canadian pharmacy reviews – my canadian pharmacy rx

  17. TylerShets Avatar
    TylerShets

    http://certifiedcanadarx.com/# thecanadianpharmacy

  18. RobertFup Avatar
    RobertFup

    pet meds official website Vet Rx Index best pet rx

  19. Williamchabe Avatar
    Williamchabe

    discount pet meds: Vet Rx Index – pet med

  20. LhaneDrync Avatar
    LhaneDrync

    It’s awesome to go to see this web site and reading the views of all colleagues concerning this article, while I am also eager of getting knowledge.
    https://play-star.ru/

  21. AndrewMuh Avatar
    AndrewMuh

    online erectile dysfunction medication: low cost ed medication – cheapest ed meds

  22. RobertFup Avatar
    RobertFup

    pet pharmacy Vet Rx Index pet prescriptions online

  23. TylerShets Avatar
    TylerShets
  24. Williamchabe Avatar
    Williamchabe

    canadian pharmacy in canada: Certified Canada Rx – Certified Canada Rx

  25. Henryaloth Avatar
    Henryaloth
  26. Henryaloth Avatar
    Henryaloth

    http://mensrxindex.com/# cheap boner pills

  27. AndrewMuh Avatar
    AndrewMuh

    Mens RX Index: top rated ed pills – online erectile dysfunction pills

  28. AnthonyBop Avatar

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

  29. TylerShets Avatar
    TylerShets
  30. Frankendat Avatar

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

  31. TylerShets Avatar
    TylerShets

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

  32. AndrewMuh Avatar
    AndrewMuh

    Certified Canada Rx: canadian pharmacy ltd – Certified Canada Rx

  33. Michaelimimb Avatar

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

  34. Buddybriep Avatar

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

  35. Henryaloth Avatar
    Henryaloth
  36. RobertFup Avatar
    RobertFup

    pet meds for dogs Vet Rx Index pet pharmacy

  37. Registrera dig Avatar

    I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  38. Williamchabe Avatar
    Williamchabe

    vet pharmacy online: dog medicine – online vet pharmacy

  39. Williamchabe Avatar
    Williamchabe

    Mens RX Index: erectile dysfunction online prescription – cheap ed pills

  40. AndrewMuh Avatar
    AndrewMuh

    cheap ed meds: where to buy ed pills – Mens RX Index

  41. Henryaloth Avatar
    Henryaloth

    https://mensrxindex.shop/# erectile dysfunction medication online

  42. Henryaloth Avatar
    Henryaloth

    https://mensrxindex.shop/# ed pills for sale

  43. TylerShets Avatar
    TylerShets

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

  44. AndrewMuh Avatar
    AndrewMuh

    dog medicine: canada pet meds – canada pet meds

  45. DavidCAH Avatar

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

  46. RobertFup Avatar
    RobertFup

    online ed medication Mens RX Index Mens RX Index

Leave a Reply

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