TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Advertisement
Checking Input with Zend_Validate
   Checking Input with Zend_Validate


Introduction

Most PHP applications will eventually have to deal with some type of external data. This data could be from a registration or login form that your visitor submitted or from a RSS feed that your application reads.

Whatever the form of input, you will usually want to check this data to ensure that it contains what you are expecting. For instance, if you are expecting a 2 digit number but receive the English dictionary, your application may not function as expected. :)

This is where validation comes in to play. Good validation ensures that your PHP application receives the data that it expects, thus preventing errors, bugs and potential security breaches.

Validation is often done using regular expressions which can quickly grow complex and are prone to errors. Thankfully, this is where the Zend_Validate class from the Zend Framework can help.

For those who haven't heard of the Zend Framework before, it is (to quote the manual) "...a high quality and open source framework for developing Web Applications and Web Services with PHP". What this means in English is that the Zend Framework is a collection of classes that make your life as a developer easier.

For the purposes of this article we will only be looking at the Zend_Validator class but you can read about the full range of classes that the Zend Framework offers over at their website.


Requirements

To use the Zend_Validate class in your PHP applications you will need to download the Zend Framework from http://framework.zend.com. Once downloaded, unzip and extract the library directly into your PHP application directory.

For example, once extracted the directory layout should look something like this:

Code:
/home/alan/webroot/myApp/library/Zend/...

Using Zend_Validate

The Zend_Validate class is able to validate many different types of data as standard including numbers, alpha-numeric values, email addresses, and IP addresses. It is also easy to extend so that you can validate any custom data.

The following example shows you how to ensure that the 'username' form field only contains alpha-numeric characters.

PHP Code:
<?php

// Set the include path so that the Zend Framework can find it's library
set_include_path('.' PATH_SEPARATOR './library' PATH_SEPARATOR get_include_path());

// Load the Alpha-Numeric (Alnum) validation class
require_once('Zend/Validate/Alnum.php');

// Create a new validation object
$validator = new Zend_Validate_Alnum();

// Check to see if the username form field only contains alpha-numeric characters
if ($validator->isValid($_POST['username']))
{
    
// Valid username - only contains A-Z and 0-9
    
echo "Valid username";
}
else
{
    
// Invalid Username - Display error messages
    
foreach ($validator->getMessages() as $message)
    {
        echo 
$message;
    }
}
As you can see from this example, using the Zend_Validate class is fairly straight forward.

The first thing we do is set the PHP include path so the Zend Framework knows where its files are located. Next we load the validator class for alpha-numeric input and create a new validator object.

We then check using the isValid() method to see if our input (in this case, $_POST['username']) contains only alpha-numeric characters. If it does, we echo a simple sucess message but if it doesn't, we use Zend_Validate's built in method getMessages() to return the errors to the user.

Zend_Validate contains two methods that you can use in case of errors. The first which you have seen above is getMessages(). This will return an array with user-friendly error messages that are designed to be echo'd directly to the user. The second method is getErrors(). This also returns an array of error messages but they are not user-friendly and are designed to be used in your application.

For example, if in our script above the username provided was "Alan @ CIT", getMessages() would provide the following message:

Code:
'Alan @ CIT' has not only alphabetic and digit characters
Where as getErrors() would provide the following message

Code:
notAlnum
As you can see, it is advisable to use getMessages() if you plan on sending the error text straight back to your users.


Validation Types

The Zend_Validate class provides a total of 18 built-in validation types covering a wide range of data formats. Examples of these can be found below.

Validating Letters and Numbers

Zend_Validate allows you to check for Alpha-Numeric input, just Alpha input, or just Numeric input.

Examples:

PHP Code:
<?php

// ...Set include path and include the Zend_Validate PHP files here...

// ----------------
// Alpha-Numeric
// Zend_Validate_Alnum takes an optional parameter - if set to True, it treats whitespace as valid
$validator = new Zend_Validate_Alnum(true);
if (
$validator->isValid($myInput))
{
    
// "Alan 123" would evaluate to true.
    // "Alan --@ 123" would evaluate to false
}

// ----------------
// Alpha
// Zend_Validate_Alpha takes an optional parameter - if set to True, it treats whitespace as valid
$validator = new Zend_Validate_Alpha();
if (
$validator->isValid($myInput))
{
    
// "Alan" would evaluate to true
    // "123 Alan" would evaluate to false
}

// ----------------
// Numbers
$validator = new Zend_Validate_Int();
if (
$validator->isValid($myInput))
{
    
// "123456" would evaluate to true
    // "ABC123" would evaluate to false
}

Validating Email Addresses, Hostnames and IP Addresses

Zend_Validate allows you to check for valid email address, hostnames and IP addresses. It also has some additional bonus features such as checking if an email address domain has MX records setup for it or checking for local hostnames.

Examples:

PHP Code:
<?php

// ...Set include path and include the Zend_Validate PHP files here...

// ----------------
// Email Addresses
// Zend_Validate_EmailAddress takes many optional parameters that allow you to 
// check that the hostname exists and that it accepts mail (using MX records)
// See the Zend Framework manual for more info 
$validator = new Zend_Validate_EmailAddress();
if (
$validator->isValid($myEmail))
{
    
// Supports all email address formats provided by RFC2822 so the following are valid:
    // alan@example.com, alan wagstaff@example.com, alan+wagstaf@example.com ...etc
}

// ----------------
// Hostnames
// Zend_Validate_Hostname takes optional parameters to allow IP addresses and
// local hostnames.  See the Zend Framework manual for more info
$validator = new Zend_Validate_Hostname();
if (
$validator->isValid($myHostname))
{
    
// "example.com" would evaluate to true
    // "asdfgh.asd" would evaluate to false
}

// ----------------
// IP Addresses
$validator = new Zend_Validate_Ip()
if (
$validator->isValid($myIP))
{
    
// "212.11.130.1" would evaluate to true
    // "123.456.789.0" would evaluate to false
}

Checking Variable Lengths

Often you will find that you need to ensure that a value is greater than x characters, or less than x characters. Zend_Validate provides you with five classes to acheive this.

Examples

PHP Code:
<?php

// ...Set include path and include the Zend_Validate PHP files here...

// ----------------
// NotEmpty
$validator = new Zend_Validate_NotEmpty();
if (
$validator->isValid($myInput))
{
    
// "abc" would evaluate to true
    // "" would evaluate to false
}

// ----------------
// StringLength
// Zend_Validate_StringLength takes 2 parameters.  The first is the minimum
// allowed length of the string and the second is the maximum allowed length
$validator = new Zend_Validate_StringLength(310);
if (
$validator->isValid($myString))
{
    
// "abcdef" would evaludate to true
    // "ab" would evaluate to false (less than 3 characters)
    // "abcdefghijkl" would evaluate to false (greater than 10 charaters)
}

// ----------------
// LessThan
// Zend_Validate_LessThan takes 1 parameter - the maximum allowed value
$validator = new Zend_Validate_LessThan(50);
if (
$validator->isValid($myValue))
{
    
// 35 would evaluate to true
    // 135 would evaluate to false
}

// ----------------
// GreaterThan
// Zend_Validate_GreaterThan takes 1 parameter - the minimum allowed value
$validator = new Zend_Validate_GreaterThan(123);
if (
$validator->isValid($myValue))
{
    
// 150 would evaluate to true
    // 30 would evaluate to false
}

// ----------------
// Between
// Zend_Validate_Between takes 2 parameters - the minimum and maximum values
$validator = new Zend_Validate_Between(1880);
if (
$validator->isValid($myNumber))
{
    
// 30 would evaluate to true
    // 86 would evaluate to false
}

And the rest...

Zend_Validate also provides classes for validating credit card numbers, dates, and much more. To see a full list, check the Zend_Validate section of the Zend Framework manual.


Checking More Than 1 Condition

You will often want to validate data against multiple criteria. For example, you may want to ensure that a username on a registration form only contains letters, and that it is between 1 and 20 characters long.

To do this, Zend_Validate allows you to chain validations together. To solve our username problem, we would use something like the following.

PHP Code:
<?php

// First we include the Zend_Validate class - this allows us to chain validations
require_once('Zend/Validate.php');

// Next we include all the validators that we require.  In this example, we
// are only checking string length and for Alpha-only characters
require_once('Zend/Validate/Alpha.php');
require_once(
'Zend/Validate/StringLength.php');

// Now we need to create our validator chain object
$validatorChain = new Zend_Validate();

// Next, we add the rules that we wish to apply to our value
$validatorChain->addValidator(new Zend_Validate_Alpha())
               ->
addValidator(new Zend_Validate_StringLength(120));
            
// Now we need to check our username.
// At this point, it will start at the begining of the chain
// by checking that the username only contains letters A-Z, 
// it will then check the string length
if ($validatorChain->isValid($_POST['username']))
{
    
// Username is valid
    
echo 'Success!';
}
else
{
    
// Username failed on one of the validators
    
foreach ($validatorChain->getMessages() as $message)
    {
        echo 
$message;
    }
}
As you can see, using validation chains allows us to create complex rules for data to ensure it is as our application expects it.


Custom Validation

There will always be a time where even using Zend_Validate chains still doesn't fit the format of your data exactly. Thankfully, the Zend_Validate section of the Zend Framework manual contains a tutorial on building your own custom Zend_Validate subclasses.


Conclusion

Hopefully this article has shown you how simple it can be to validate external input in your applications. Gone are the days of long complex regular expressions to validate an e-mail address, now you can just use isValid($email) and it will do it all for you!


Links and Further Reading

Zend Framework Download
Zend_Validate Manual
Creating Custom Validators
Report this Article
Last 5 Article Reviews Read All Reviews
   Must of missed that whole section then.
Review added by zendkush on 08-26-2008
Sorry about that :) Validator chains are there.
   Good for beginners
Review added by zendkush on 08-26-2008
You totally left out some quality parts though.

Validator Chains, MetaKeys, Filtering, and Zend_Filter_Input to start.
   Question...
Review added by danielneri on 01-27-2008
Wouldn't so much validation slow down the whole script though?

All times are GMT. The time now is 04:38 PM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design