PHP Sanitation and Validation

The intention for this post is to record the PHP Sanitation and Validation techniques I’ve used against various variable types for future reference. Until now I’ve always found myself digging through code to remind myself of what I did last time.

There are two key approaches regular expressions and the filter_var function from PHP. If you are going to use the filter_var function provided with PHP you should use both Sanitize and Validate. If you are unsure of the difference you should look here but you are too lazy right so very quickly:

  • Sanitize – cleans out the input incase the user ‘accidentally’ typed a wrong char.
  • Validate – makes sure it fits the right format.

I’ve never had much success with this approach as the email and float filters seem to reject valid parameters.

Validating Floats

To validate floats where validateRegexField is a function of mine (See Bottom) I call the function with

Note how I am using the ^ and $ to prevent other text contaminating the field. If you are interested in what I mean take them out and try 4.5 bad which will then validate. Put them back in and it will error. I’m also passing the first and last variables by reference so I can change their values in the function (bottom of page).

Dates

General consensus here is that Regex is not the best way to do this because it fails to find some types of invalid field. This method attempts to turn the date into a string and then back into a date again. This leaves our users free to enter a date in whatever format they like and we then just rearrange it. Sadly it doesn’t work for when someone enters only yyyy-mm as dd default to 01 so I have added in a length check for 10. This function is based on information found on the checkdate docs page and iamcanadian1973 in particular.

validateRegexField Function

This validateField function takes some variables and checks for a valid entry.

About CDB 361 Articles
Self-Employed Software Developer, Spark, Property Management, Hobby Forestry, Ex-Teacher, Engineering - Wood, Metal, Electrics & Computers. Outdoors - Walk, Cycle, Kitesurf,

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.