PHP Validate Input

Jan 19, 2009 Author: vvaswani

In addition to escaping characters, another great to way to protect input is to validate it. With many applications, you actually already know what kind of data you are expecting on input. So the simplest way to protect yourself against attacks is to make sure your users can only enter the appropriate data.

For example, say we are creating an application that lists users birthdays and allows users to add their own. We will be wanting to accept a month as a digit between 1-12, a day between 1-31 and a year in the format of YYYY.

Having this kind of logic in your application is simple and regular expressions (regex) are the perfect way to handle input validation. Take the following example:

  1. if ( ! preg_match( "/^[0-9]{1,2}$/"$_GET['month'] ) )  
  2. {  
  3.     // handle error  
  4. }  
  5. if ( ! preg_match( "/^[0-9]{1,2}$/"$_GET['day'] ) )  
  6. {  
  7.     // handle error  
  8. }  
  9. if ( ! preg_match( "/^[0-9]{4}$/"$_GET['year'] ) )  
  10. {  
  11.     // handle error  
  12. }  

In this example, we simply checked (in the first two if statements) for integers [0-9] with a length of one or two {1,2} and we did the same in the third if statement, but checked for a strict length of 4 characters {4}.

In all instances, if the data doesn't match the format we want, we return some kind of error. This type of validation leaves very little room for any type of SQL attack.

Regex expressions like those above can be a little difficult to grasp at first, but explaining them is out of the scope of this article. The php manual has some additional resources to help you with validation. The PEAR database also has a few packages such as the Validate package to help with emails, dates, and URLS.

Below is an example of the above script in action using 200 as an input for a month, abc for the day and just 09 for the year.

views 5177
  1. Add New Comment