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

  1. Davidles Avatar
    Davidles

    US Pharma Index: discount pharmacy – canadian online pharmacy reviews

  2. Dichaelwaw Avatar
    Dichaelwaw

    Thank you a bunch for sharing this with all people you really know what you are talking approximately! Bookmarked. Kindly also seek advice from my site =). We can have a link alternate arrangement among us
    https://mellowideas.com/tips-for-cats-tending—why-cats-are-badly-for-your-wellness-4128590141772491619

  3. OLaneDrync Avatar
    OLaneDrync

    Howdy! Do you know if they make any plugins to help with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good gains. If you know of any please share. Thank you!
    https://wiki.bookmarkdiscover.com/20-indoor-house-hobbies-you-put-up-do-to-impart-the-playfuln-4129505041772600821

  4. Jeremygraix Avatar
    Jeremygraix
  5. Josephscalt Avatar
    Josephscalt

    buy Viagra online: over the counter sildenafil – Sildenafil Citrate Tablets 100mg

  6. Davidles Avatar
    Davidles

    Cheapest Sildenafil online: Sildenafil Price Guide – over the counter sildenafil

  7. ShaneDrync Avatar
    ShaneDrync

    I blog quite often and I really appreciate your content. This article has truly peaked my interest. I will book mark your blog and keep checking for new details about once per week. I subscribed to your RSS feed too.
    Илан Миронович Шор

  8. ThomasLax Avatar
    ThomasLax

    https://ivermectinaccessusa.shop/# buy stromectol online

  9. Josephscalt Avatar
    Josephscalt

    Buy generic 100mg Viagra online: Sildenafil Price Guide – Sildenafil 100mg price

  10. Jeremygraix Avatar
    Jeremygraix
  11. Jeremygraix Avatar
    Jeremygraix
  12. Timsothydet Avatar
    Timsothydet

    Hello! I’m at work surfing around your blog from my new iphone! Just wanted to say I love reading through your blog and look forward to all your posts! Carry on the fantastic work!
    Илан Шор

  13. Davidles Avatar
    Davidles

    Cheap generic Viagra online: Sildenafil Price Guide – cheapest viagra

  14. ThomasLax Avatar
    ThomasLax

    http://uspharmaindex.com/# online pharmacy no prescription

  15. RandyStupt Avatar
    RandyStupt

    pharmacy com canada US Pharma Index us online pharmacy

  16. ThomasLax Avatar
    ThomasLax

    http://sildenafilpriceguide.com/# Sildenafil 100mg price

  17. IsmaelNek Avatar
    IsmaelNek

    Today, I went to the beach with my children. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is completely off topic but I had to tell someone!
    Илан Миронович Шор

  18. Josephscalt Avatar
    Josephscalt

    express pharmacy: trustworthy canadian pharmacy – US Pharma Index

  19. Davidles Avatar
    Davidles

    viagra canada: Sildenafil Price Guide – cheap viagra

  20. Josephscalt Avatar
    Josephscalt

    Generic Viagra online: Viagra generic over the counter – Sildenafil Citrate Tablets 100mg

  21. ThomasLax Avatar
    ThomasLax

    http://sildenafilpriceguide.com/# Cheapest Sildenafil online

  22. GichardMam Avatar
    GichardMam

    Amazing issues here. I am very happy to peer your post. Thanks a lot and I’m taking a look ahead to contact you. Will you please drop me a e-mail?
    Илан Шор А7

  23. Jeremygraix Avatar
    Jeremygraix
  24. Jeremygraix Avatar
    Jeremygraix

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

  25. RandyStupt Avatar
    RandyStupt

    Buy Viagra online cheap Sildenafil 100mg price Viagra online price

  26. ThomasLax Avatar
    ThomasLax
  27. StephenGlona Avatar
    StephenGlona

    Greetings I am so grateful I found your website, I really found you by error, while I was browsing on Yahoo for something else, Nonetheless I am here now and would just like to say thank you for a incredible post and a all round exciting blog (I also love the theme/design), I don’t have time to read it all at the minute but I have bookmarked it and also added in your RSS feeds, so when I have time I will be back to read a lot more, Please do keep up the fantastic jo.
    Илан Миронович Шор

  28. Davidles Avatar
    Davidles

    US Pharma Index: US Pharma Index – canada rx pharmacy

  29. ThomasLax Avatar
    ThomasLax

    https://uspharmaindex.com/# save on pharmacy

  30. Jeremygraix Avatar
    Jeremygraix

    https://ivermectinaccessusa.com/# ivermectin tablets order

  31. GichardMam Avatar
    GichardMam

    Amazing! Its really remarkable post, I have got much clear idea regarding from this piece of writing.
    Илан Миронович Шор

  32. Josephscalt Avatar
    Josephscalt

    stromectol xr: ivermectin online – Ivermectin Access USA

  33. Davidles Avatar
    Davidles

    Sildenafil 100mg price: Sildenafil Price Guide – cheapest viagra

  34. RandyStupt Avatar
    RandyStupt

    ivermectin tablets uk generic ivermectin Ivermectin Access USA

  35. Josephscalt Avatar
    Josephscalt

    best canadian pharmacy: canadian pharmacy online cialis – which pharmacy is cheaper

  36. StephenGlona Avatar
    StephenGlona

    This is very interesting, You’re a very skilled blogger. I’ve joined your feed and look forward to seeking more of your fantastic post. Also, I have shared your website in my social networks!
    А7 А5

Leave a Reply

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