Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 15 ■ INTRODUCTION TO THE ZEND FRAMEWORK^229

Validating Input.


Before you can submit the posted information to your database, you must make sure that the
information is valid so that your database remains consistent. The Zend_Db infrastructure will
provide protection against SQL injection, so this validation layer is primarily to make sure the
data is reasonable and is safe to be displayed on other pages.
Accepting user input in a Zend Framework application consists of two parts:


  • Filtering, which involves the modification of data, to trim whitespace from the ends of
    strings or to strip HTML tags, for example

  • Validation, which occurs after filtering and ensures that the data is reasonable, so that it
    won’t cause issues like cross-site scripting


Both of these actions can be achieved separately with the Zend_Filter and Zend_Validate
classes. However, they are more commonly used together through the Zend_Filter_Input
class, which is designed to filter arrays of information, such as an entire form or set of URL
parameters.

Using Zend_Filter_Input
To use Zend_Filter_Input, you need to first define two associative arrays: one for your filters
and one for your validators. The keys in these arrays refer to the fields you wish to validate,
whereas the values define the rules to apply. Listing 15-16 shows how to validate the customers
form.

Listing 15-16. Validating a Form (in CustomersController.php)

public function addAction() {
$request = $this->getRequest();

//Determine if processing a post request
if($request->isPost()) {

//Filter tags from the name field
$filters = array(
'name' => 'StripTags'
);

//Validate name is not less than 1 character and not more than 64
$validation = array(
'name' => array (
array('StringLength', 1, 64)
)
);

//Initialize Zend_Filter_Input (ZFI) passing it the entire getPost() array
$zfi = new Zend_Filter_Input($filters, $validation, $request->getPost());

McArthur_819-9C15.fm Page 229 Thursday, February 28, 2008 7:44 AM

Free download pdf