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

1,790 responses to “Input validation with filter functions”

  1. Williamopete Avatar
    Williamopete

    ViagraNewark Viagra online price Viagra online price

  2. JamesHow Avatar

    Cor Pharmacy: CorPharmacy – CorPharmacy

  3. SteveMar Avatar
    SteveMar

    online pharmacies no prescriptions https://edpillsafib.xyz/# Ed Pills Afib

  4. DanielLox Avatar

    ViagraNewark: ViagraNewark – Order Viagra 50 mg online

  5. Williamopete Avatar
    Williamopete

    Ed Pills Afib Ed Pills Afib Ed Pills Afib

  6. SteveMar Avatar
    SteveMar

    recommended canadian online pharmacies https://edpillsafib.xyz/# EdPillsAfib

  7. JamesHow Avatar

    CorPharmacy: Cor Pharmacy – tops pharmacy

  8. DanielLox Avatar

    EdPillsAfib: Ed Pills Afib – EdPillsAfib

  9. RonaldFiple Avatar

    аренда горизонтальных строительных лесов аренда регулируемых строительных лесов

  10. Williamopete Avatar
    Williamopete

    Ed Pills Afib Ed Pills Afib EdPillsAfib

  11. LewisGuatt Avatar
    LewisGuatt

    Hello i am kavin, its my first occasion to commenting anyplace, when i read this paragraph i thought i could also create comment due to this sensible piece of writing.
    https://www.vapear.com.co/melbet-2025-obzor-bk/

  12. StevenGroxy Avatar

    ко ланта отзывы Погода Ко Ланта — климат тропический: сухой сезон с ноября по апрель и влажный сезон с мая по октябрь. Температуры держатся примерно в диапазоне 25–32°C круглый год, влажность высокая, часто дует прохладный ветер зимой. Сухой сезон подходит для купания и подводного плавания, дождливый период приносит ливни и порывистые ветры, что влияет на паромы и поездки на лодках. Для любителей сноркелинга хороши периоды в рамках спокойной погоды и меньшей волнистости, а сезон дождей может предложить менее многолюдные пляжи и зеленые пейзажи после ливней.

  13. JamesHow Avatar

    Sildenafil Citrate Tablets 100mg: ViagraNewark – Viagra Newark

  14. SteveMar Avatar
    SteveMar

    cheap prescription drugs online https://viagranewark.com/# cheapest viagra

  15. StevenGroxy Avatar

    пляжи ко ланты погода ко ланта — климат регулируется муссонной системой Индии. Сухой сезон — с ноября по апрель — самое благоприятное время для купания и прогулок: море обычно спокойное, дни ясные, температура комфортная. Влажный сезон — с мая по октябрь — приносит частые ливни и порывистые ветра, но вода остаётся тёплой; дни часто жаркие и влажные. Температуры 24–32°C круглый год, но бывают периоды, когда влажность поднимается выше; вода может быть слегка мутной после дождей. Лучшее время для сноркелинга — сухой сезон, когда море чистое и прозрачное. Всегда полезно проверить прогноза ветра и приливов перед планированием активностей.

  16. DanielLox Avatar

    CorPharmacy: Cor Pharmacy – Cor Pharmacy

  17. Williamopete Avatar
    Williamopete

    canadian pharmacy cialis 40 mg Cor Pharmacy Cor Pharmacy

  18. SteveMar Avatar
    SteveMar

    ed drugs online http://corpharmacy.com/# canadian pharmacy online cialis

  19. JamesHow Avatar

    best price for viagra 100mg: ViagraNewark – ViagraNewark

  20. WilliamBof Avatar

    1xbet промокод при регистрации Активируйте промокод на https://www.exchangle.com/bergkompressor и заберите бонус до 32 500 рублей при регистрации для комфортной игры.

  21. DanielLox Avatar

    Cheap generic Viagra: ViagraNewark – Cheap generic Viagra

  22. Williamopete Avatar
    Williamopete

    ViagraNewark Order Viagra 50 mg online ViagraNewark

  23. ThomasSat Avatar

    удаленная работа вакансии удаленная работа в интернете

  24. JamesHow Avatar

    Ed Pills Afib: EdPillsAfib – Ed Pills Afib

  25. SteveMar Avatar
    SteveMar

    mail order drug store https://corpharmacy.xyz/# cheapest prescription pharmacy

  26. DanielLox Avatar

    generic ed meds online: EdPillsAfib – buy ed medication online

  27. Williamopete Avatar
    Williamopete

    EdPillsAfib online prescription for ed EdPillsAfib

  28. SteveMar Avatar
    SteveMar

    canadian pharmacy no prescrition https://edpillsafib.xyz/# cost of ed meds

  29. JamesHow Avatar

    CorPharmacy: Cor Pharmacy – CorPharmacy

  30. Williamopete Avatar
    Williamopete

    ed prescriptions online EdPillsAfib Ed Pills Afib

  31. JamesHow Avatar

    Cor Pharmacy: CorPharmacy – CorPharmacy

  32. SteveMar Avatar
    SteveMar

    viagra mexican pharmacy http://corpharmacy.com/# canadian family pharmacy

  33. StevenGroxy Avatar

    ко ланта аэропорт Остров Ко Ланта в Таиланде — это пара островов в Андаманском море, которые образуют спокойное и размеренное направление отдыха у побережья Криси?-краби. Главный остров Ko Lanta Yai соединён мостами и местными дорогами с небольшим Ko Lanta Noi, образуя двойной контур, который обеспечивает разнообразие атмосферы: от уютных деревенских уголков до ухоженных курортов на побережье. Остров славится длинной береговой линией, пальмовыми бухтами и зелёными холмами, на которых прячутся мангровые леса и тропические сады. Здесь можно найти варианты на любой вкус: от гестхаусов у воды до роскошных вилл в укромных бухтах, а также тихие эко-лагеря, где можно отключиться от суеты. Путешествие сюда обычно начинается с прибытия в Krabi или Phuket на самолёте, затем переезд к пирсу и паромная переправа через побережье — часть маршрута добавляет путешествованию романтики и медленного темпа.

Leave a Reply

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