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

  1. Charlescliny Avatar

    buy abortion pills: buy abortion pills – Socal Abortion Pill

  2. DouglasJag Avatar

    metformin 500 mg over the counter: metformin tab price – metformin 1000mg without prescription

  3. Patricklib Avatar
    Patricklib

    best online pharmacy india https://bswfinasteride.xyz/# BSW Finasteride

  4. Davidrulge Avatar

    buy abortion pills buy abortion pills buy abortion pills

  5. Charlescliny Avatar

    order cheap propecia price: BSW Finasteride – cost generic propecia online

  6. Davidrulge Avatar

    BSW Finasteride BSW Finasteride cost generic propecia pills

  7. Patricklib Avatar
    Patricklib

    india pharmacy mail order https://socalabortionpill.xyz/# SocalAbortionPill

  8. Charlescliny Avatar

    Ucla Metformin: Ucla Metformin – buy metformin 500 mg online

  9. Patricklib Avatar
    Patricklib

    Online medicine home delivery http://bswfinasteride.com/# cost propecia without dr prescription

  10. DouglasJag Avatar

    Socal Abortion Pill: buy cytotec pills online cheap – buy abortion pills

  11. DouglasJag Avatar

    PMA Ivermectin: is stromectol over the counter – PmaIvermectin

  12. Charlescliny Avatar

    BswFinasteride: cost propecia online – buy cheap propecia online

  13. Patricklib Avatar
    Patricklib

    buy prescription drugs from india https://pmaivermectin.xyz/# stromectol xl

  14. Charlescliny Avatar

    Socal Abortion Pill: buy abortion pills – Socal Abortion Pill

  15. Patricklib Avatar
    Patricklib

    buy medicines online in india https://uclametformin.com/# Ucla Metformin

  16. Davidrulge Avatar

    BSW Finasteride BSW Finasteride BSW Finasteride

  17. Robertfluby Avatar

    1xBet промокод при регистрации Использование промокода при регистрации на http://www.smstender.ru/js/pages/?1xbet_promokod_pri_registracii_na_segodnya_besplatno.html позволяет получить бонус до 32 500 рублей, чтобы начать игру с максимальной суммой.

  18. DouglasJag Avatar

    Ucla Metformin: UclaMetformin – metformin otc uk

  19. cvzcentr-456 Avatar

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

  20. filmproductioncortina-813 Avatar

    ORBS Production https://filmproductioncortina.com is a full-service film, photo and video production company in Cortina d’Ampezzo and the Dolomites. We create commercials, branded content, sports and winter campaigns with local crew, alpine logistics, aerial/FPV filming and end-to-end production support across the Alps. Learn more at filmproductioncortina.com

  21. DouglasJag Avatar

    PmaIvermectin: PMA Ivermectin – ivermectin prices

  22. Charlescliny Avatar

    BSW Finasteride: BswFinasteride – BSW Finasteride

  23. Davidrulge Avatar

    buy abortion pills Cytotec 200mcg price Socal Abortion Pill

  24. Patricklib Avatar
    Patricklib

    п»їlegitimate online pharmacies india https://socalabortionpill.xyz/# buy cytotec over the counter

  25. Patricklib Avatar
    Patricklib

    indianpharmacy com https://bswfinasteride.com/# BswFinasteride

  26. Charlescliny Avatar

    Socal Abortion Pill: Socal Abortion Pill – buy abortion pills

  27. Patricklib Avatar
    Patricklib

    buy medicines online in india http://bswfinasteride.com/# BswFinasteride

  28. Charlescliny Avatar

    ivermectin for cancer: how to get ivermectin prescription – PmaIvermectin

  29. DouglasJag Avatar

    buying generic propecia: order cheap propecia pills – BswFinasteride

  30. DouglasJag Avatar

    metformin 1000 mg from canada: metformin 1000 mg cost – metformin 1000 tablet

  31. Patricklib Avatar
    Patricklib

    reputable indian online pharmacy https://pmaivermectin.com/# PmaIvermectin

  32. cvzcentr-673 Avatar

    ЦВЗ центр https://cvzcentr.ru в Краснодаре — команда специалистов, которая работает с вегетативными расстройствами комплексно. Детальная диагностика, сопровождение пациента и пошаговый план улучшения самочувствия.

  33. Charlescliny Avatar

    BSW Finasteride: BswFinasteride – BswFinasteride

  34. nairabet-play-156 Avatar

    Nairabet offers https://nairabet-play.com sports betting and virtual games with a simple interface and a wide range of markets. The platform provides live and pre-match options, quick access to odds, and regular updates. Visit the site to explore current features and decide if it suits your preferences.

Leave a Reply

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