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

4,639 responses to “Input validation with filter functions”

  1. AllanMus Avatar

    p e r o розыгрыши ключей

  2. HarryZoowl Avatar
    HarryZoowl

    online pharmacy india: top 10 pharmacies in india – buy prescription drugs from india

  3. RandyLew Avatar
    RandyLew

    https://usmedsoutlet.shop/# discount pharmacy

  4. VaughnOvaph Avatar
    VaughnOvaph
  5. HarryZoowl Avatar
    HarryZoowl

    indian pharmacy paypal: Indo-Generic Export – Online medicine order

  6. StephenPep Avatar
    StephenPep

    US Meds Outlet canadian pharmacy viagra 50 mg online pharmacy without scripts

  7. VaughnOvaph Avatar
    VaughnOvaph

    https://bajameddirect.com/# mexico pet pharmacy

  8. RandyLew Avatar
    RandyLew

    http://indogenericexport.com/# over the counter muscle relaxers that work

  9. WilliamNex Avatar
    WilliamNex

    BajaMed Direct: BajaMed Direct – BajaMed Direct

  10. blackcoin Avatar

    Many of the top online casinos Australia offers are fully mobile-optimized and work straight from your phone’s browser —
    no app needed. Yes, most legit online casinos in Australia
    follow KYC (Know Your Customer) protocols. These days, whenever
    I land on one of the best Australian online casino sites, I do a quick check to see candy96.fun which
    games offer the best payout percentages. Once I understood how RTP (Return to Player) actually worked, it completely changed the way I approached online casino
    games.
    Our content is for informational/entertainment purposes only – NOT financial, legal, or gambling advice.

    Blackcoin.co a fully independent review platform with no ownership ties to any
    casino operator or software provider. Yes,
    PayID uses advanced encryption and secure banking protocols to protect your financial
    information. The funding process is extremely easy and doesn’t
    differ much from casino to casino. It’s convenient candy96.fun and local, making it faster and easier for Aussies to deposit and withdraw.
    PayID is a legal payment processing system that is owned
    by a local Australian company.
    The mix of speed and security makes PayID a trusted choice for both casual and high-stakes gamers.

    Unlike typical financial institution transfers that can take several days, PayID
    enables down payments to be refined almost quickly. This
    eliminates the need to remember long BSB and account numbers when moving cash, making transactions quicker and easier.

  11. WilliamNex Avatar
    WilliamNex

    mexican pharmacies that ship to us: BajaMed Direct – best pharmacy in mexico

  12. HarryZoowl Avatar
    HarryZoowl

    best online pharmacy india: Indo-Generic Export – indian pharmacy online

  13. RandyLew Avatar
    RandyLew

    https://indogenericexport.com/# п»їbest muscle relaxer

  14. VaughnOvaph Avatar
    VaughnOvaph
  15. StephenPep Avatar
    StephenPep

    india online pharmacy Indo-Generic Export indian pharmacy

  16. DanielBab Avatar

    какие слоты сейчас дают Почему Casino-Gid.best – ваш лучший помощник? Мы понимаем, что мир онлайн-казино может быть запутанным, особенно для новичков. Наша миссия – сделать его доступным и понятным для каждого. На Casino-Gid.best вы найдете:

  17. HarryZoowl Avatar
    HarryZoowl

    indianpharmacy com: US Meds Outlet – US Meds Outlet

  18. RandyLew Avatar
    RandyLew

    http://bajameddirect.com/# tijuana pharmacy online

  19. WilliamNex Avatar
    WilliamNex

    BajaMed Direct: BajaMed Direct – BajaMed Direct

  20. VaughnOvaph Avatar
    VaughnOvaph

    https://bajameddirect.shop/# mexico pharmacies

  21. HarryZoowl Avatar
    HarryZoowl

    indianpharmacy com: Indo-Generic Export – legitimate online pharmacies india

  22. VaughnOvaph Avatar
    VaughnOvaph
  23. WilliamNex Avatar
    WilliamNex

    indian pharmacy: Online medicine order – top online pharmacy india

  24. JimmyCof Avatar

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

  25. StephenPep Avatar
    StephenPep

    india pharmacy india pharmacy indian pharmacy paypal

  26. RonaldCrido Avatar

    Новый адрес работает отлично уже целую неделю. 7k рабочее зеркало без сбоев и лагов вообще.

  27. HarryZoowl Avatar
    HarryZoowl

    BajaMed Direct: BajaMed Direct – can i order online from a mexican pharmacy

  28. RandyLew Avatar
    RandyLew

    https://bajameddirect.shop/# mexico pharmacy price list

  29. MalcolmTam Avatar

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

  30. WilliamNex Avatar
    WilliamNex

    BajaMed Direct: BajaMed Direct – pharmacy mexico

  31. StephenPep Avatar
    StephenPep

    US Meds Outlet US Meds Outlet US Meds Outlet

  32. VaughnOvaph Avatar
    VaughnOvaph

    http://indogenericexport.com/# top 10 pharmacies in india

  33. WilliamNex Avatar
    WilliamNex

    mexican medicine: mexico pharmacies – pharmacy in mexico that ships to us

  34. RandyLew Avatar
    RandyLew

    http://indogenericexport.com/# muscle relaxer medication

  35. HarryZoowl Avatar
    HarryZoowl

    walmart online pharmacy: US Meds Outlet – canadian pharmacy king reviews

  36. CharlesANymn Avatar

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

  37. RonaldCrido Avatar

    С первого депозита 1000 рублей дали бонус 150% плюс 150 FS. Отличный старт для новичка.

  38. VaughnOvaph Avatar
    VaughnOvaph

    https://usmedsoutlet.com/# reliable rx pharmacy

  39. HarryZoowl Avatar
    HarryZoowl

    no rx pharmacy: canadian pharmacy discount code – US Meds Outlet

  40. VaughnOvaph Avatar
    VaughnOvaph
  41. WilliamNex Avatar
    WilliamNex

    mexican pharmacy prices: BajaMed Direct – pharmacy in mexico

  42. StephenPep Avatar
    StephenPep

    online pharmacy in turkey US Meds Outlet canadian 24 hour pharmacy

Leave a Reply

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