How to validate text without regular expressions using php

Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

How to validate text without regular expressions using php

Post by Neo » Sun Feb 28, 2010 11:44 pm

Filtering data from user input and other external sources is the most important part of writing secure code, but it's also handy to make sure users supply the correct type of info to a registration form for example. Sometimes it's simply making sure something is a number or of a certain length, but other times it's something that follows a specific pattern (like an email address). This used to be a job for complex regular expressions, but fortunately, there is an easier and more reliable solution.

PHP 5.2.0 and up comes with a very convenient set of data filtering functions. These functions allow you to easily validate common things such as emails and URLs, that would otherwise require complex regular expressions that don't always work. This tutorial will focus on the simplest function filter_var().

The filter_var function looks like this:

mixed filter_var ( mixed $variable [, int $filter= FILTER_DEFAULT [, mixed $options ]] )
  • $variable - Input value to validate
  • $filter - Filter ID to use for validation
  • $options - Option flags for filter, or callback functions for callback filter
  • Returns - Filtered data or FALSE if filter fails
For a complete reference of filter flags and options, see http://www.w3schools.com/php/php_ref_filter.asp

There are basically two types of filters you can use, "sanitize" and "validate" filters. Sanitize filters basically remove unwanted characters from a string so it is "safe" for certain uses. Validate filters are used just to check is the text is valid for the specified filter and returns FALSE if it is not. There is also a filter called FILTER_CALLBACK that allows you to create custom functions to run on the input text.

Here are some examples of usage:

Code: Select all

// check if an email address is valid
$email = "[email protected]";
if(filter_var($email, FILTER_VALIDATE_EMAIL) !==  false) {
   echo "Email is valid!";
}
 
// check if URL is valid and includes scheme and host
// (note use of "|" character to use multiple flags)
$url = "http://example.com";
if(filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED | FILTER_FLAG_HOST_REQUIRED) !== false) {
   echo "URL is valid!";
}
 
// remove unsafe characters from an email address
$email = "someone@s()ome;where.com";
echo filter_var($email, FILTER_SANITIZE_EMAIL); // outputs: [email protected] 
As you can see, this is a very simple method of validation. For related functions, see the PHP manual.
Post Reply

Return to “PHP & MySQL”