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

  1. ClydeTew Avatar

    Scented prints Strategy, scent technologies and successful implementation across all product stages by Aromamedia

  2. Taylorsmump Avatar
    Taylorsmump
  3. MichaelKek Avatar
    MichaelKek

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

  4. DiegoMog Avatar
    DiegoMog

    mexican pharmacy prices: mexican pharmacy online – mexican pharmacy las vegas

  5. Larryfig Avatar
    Larryfig

    pharmacy in mexico city medicine mexico My Mexican Pharmacy

  6. Edwardtom Avatar
    Edwardtom

    pet rx: pet prescriptions online – canada pet meds

  7. MichaelKek Avatar
    MichaelKek
  8. DiegoMog Avatar
    DiegoMog

    mexico medication: mexican pharmacy online – My Mexican Pharmacy

  9. Edwardtom Avatar
    Edwardtom

    reliable canadian pharmacy: CertiCanPharmacy – CertiCanPharmacy

  10. Taylorsmump Avatar
    Taylorsmump

    https://vetfreemeds.com/# pet meds for dogs

  11. Taylorsmump Avatar
    Taylorsmump
  12. Larryfig Avatar
    Larryfig

    My Mexican Pharmacy mexico pharmacy tijuana pharmacy online

  13. ThomasWeF Avatar

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

  14. MichaelKek Avatar
    MichaelKek

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

  15. Taylorsmump Avatar
    Taylorsmump

    https://mymexicanpharmacy.com/# My Mexican Pharmacy

  16. DiegoMog Avatar
    DiegoMog

    pet drugs online: pet meds online – pet med

  17. Edwardtom Avatar
    Edwardtom

    CertiCanPharmacy: safe canadian pharmacies – CertiCanPharmacy

  18. MichaelKek Avatar
    MichaelKek
  19. ThomasWeF Avatar

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

  20. ThomasLax Avatar
    ThomasLax
  21. Jeremygraix Avatar
    Jeremygraix
  22. Jeremygraix Avatar
    Jeremygraix

    http://ivermectinaccessusa.com/# cost of ivermectin cream

  23. Dichaelwaw Avatar
    Dichaelwaw

    OneConverter.com is a website that helps you convert files quickly and accurately. It has different tools to convert files in one place. The site has a lot of converters, making it easy to change file types for work — whether you are preparing documents, making media for the web, or sharing files across devices and apps. You can choose a converter, upload a file, and get the result without installing software. OneConverter also has a Unit Converter with tools. You can convert length, weight, temperature, and more. The calculator-style workflow helps you compare units instantly. This is useful for tasks like engineering, shopping, travel, cooking, and business reporting. OneConverter is built for convenience and speed. It supports conversions for users who want to get things done efficiently and reliably. If you need a converter for file and unit conversions, OneConverter.com is a good solution. It provides a way to convert files and calculate unit metrics and helps keep your work moving with a modern conversion website.
    OneConverter Free Unit and File converter online

  24. Davidles Avatar
    Davidles

    buy viagra here: Sildenafil Price Guide – order viagra

  25. PatrickHoina Avatar
    PatrickHoina

    трансы самара Каждый трек — это путешествие, построенное на постепенном нарастании напряжения и последующем катарсисе, приводящем к взрыву эмоций.

  26. IsmaelNek Avatar
    IsmaelNek

    WebP to PNG Hero is an easy online converter. It turns images into PNG files in seconds. You can use it if you need compatibility for design tools, website uploads, or client deliverables. This service helps you switch from WebP to PNG quickly. You do not need to install software or deal with settings. Just upload your file, run the conversion, and download a clean PNG. WebP to PNG Hero is built for speed and smooth workflows. It processes WebP to PNG conversions quickly and keeps the output sharp and accurate. The conversion preserves details, clear edges, and natural colors. This way, icons, graphics, screenshots, and photos look crisp after export. PNG is a choice for web publishing, UI assets, presentations, or content creation. WebP to PNG Hero makes image conversion easy. It is useful for designers, developers, marketers, or everyday users. It is a solution when platforms or apps do not fully support WebP. You may also want a more widely accepted format for editing and sharing. You can convert WebP to PNG online with confidence. Keep your visuals looking professional with a converter focused on speed, quality, and convenience. Use WebP to PNG Hero to convert WebP to PNG. It helps with image conversion needs. WebP to PNG Hero is a tool.
    WebP to PNG Hero best online image converter

  27. Josephscalt Avatar
    Josephscalt

    Cheapest Sildenafil online: generic sildenafil – Buy Viagra online cheap

  28. Davidles Avatar
    Davidles

    purchase oral ivermectin: cost of stromectol medication – ivermectin pill cost

  29. Jeremygraix Avatar
    Jeremygraix
  30. RandyStupt Avatar
    RandyStupt

    stromectol over the counter ivermectin nz Ivermectin Access USA

  31. Josephscalt Avatar
    Josephscalt

    Viagra without a doctor prescription Canada: cheapest viagra – Viagra tablet online

  32. Timsothydet Avatar
    Timsothydet

    JPG Hero Compress is a simple tool that you can use online to make your JPG files smaller. This is helpful when you are getting ready to put photos on a website or send them in an email. You can use JPG Hero Compress to make your pictures smaller so they load faster on the internet. The tool is made to be fast so you can get your pictures compressed quickly. You can even use it with a lot of pictures at the time. JPG Hero Compress tries to make your pictures smaller without making them look bad. It wants to keep your pictures looking sharp. The colors looking natural. JPG Hero Compress is a choice, for people who want their image files to be smaller. When you use JPG Hero Compress to make your JPG files smaller it can help your website load faster. It can also help you save space on your computer and make it easier to upload your pictures to the internet. JPG Hero Compress is a tool to use when you want to compress JPG files online and you want to keep the quality of your pictures. You can use JPG Hero Compress to make your pictures smaller. It will be really easy to do.
    JPG Hero Compress online tool

  33. ThomasLax Avatar
    ThomasLax

    http://ivermectinaccessusa.com/# Ivermectin Access USA

  34. Jeremygraix Avatar
    Jeremygraix

    https://sildenafilpriceguide.shop/# Generic Viagra for sale

  35. Jeremygraix Avatar
    Jeremygraix

    https://ivermectinaccessusa.com/# ivermectin for humans

  36. RandyStupt Avatar
    RandyStupt

    US Pharma Index pharmacy rx world canada US Pharma Index

  37. OrlandoLal Avatar

    заказать пиццу саратов «Малевич пицца Саратов» и «Римини пицца» — это лишь некоторые из наших звездных предложений, доступных для заказа с нашего «пицца Саратов официальный сайт».

  38. Ruebengeamy Avatar

    пицца «Пицца с доставкой Саратов» – это наша главная специализация, гарантирующая вам «Вкусную пиццу» в любое время.

  39. Davidles Avatar
    Davidles

    sildenafil over the counter: Sildenafil Price Guide – Viagra online price

  40. StephenGlona Avatar
    StephenGlona

    WebP to JPG Hero is an online tool that helps you convert WebP images to JPG images quickly. You do not have to worry about the image quality. If you often download WebP files from the internet and you need to edit them or share them WebP to JPG Hero makes this easy for you. All you have to do is upload your image and then download the JPG image. The best thing about WebP to JPG Hero is that it is very fast. This tool is made to process your images so you can use them on your website or on social media. At the time WebP to JPG Hero makes sure that your images still look great after they are converted. The colors are still accurate. The details are still sharp. WebP to JPG Hero is great for people who create things like artists and writers and for people who market things. It is also good for teams of people who work together. You can use WebP to JPG Hero to make sure that your images can be used with any app or platform. This tool helps you get your work done quickly and easily. When you need to convert images to JPG images WebP to JPG Hero is a good choice because it works well and it is easy to use. WebP to JPG Hero is a tool, for everyday use because it is fast and it makes sure that your images look great.
    WebP to JPG Hero online converter

  41. DavidDak Avatar

    пиццерии рядом Желаете «заказать пиццу» прямо сейчас? Воспользуйтесь удобной функцией «пицца онлайн» или позвоните нам по «пицца телефону», чтобы оформить «заказ пиццы» с доставкой на дом.

  42. Josephscalt Avatar
    Josephscalt

    maple leaf pharmacy in canada: pharmacy online shopping usa – online pharmacy pain relief

  43. Jeremygraix Avatar
    Jeremygraix
  44. Josephscalt Avatar
    Josephscalt

    stromectol coronavirus: Ivermectin Access USA – stromectol 6 mg tablet

  45. ThomasLax Avatar
    ThomasLax

    https://sildenafilpriceguide.com/# over the counter sildenafil

  46. Davidles Avatar
    Davidles

    online pharmacy for sale: US Pharma Index – online pharmacy usa

Leave a Reply

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