Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling input with the Zend Framework (Post,get,etc)

Tags:

im re-factoring php on zend code and all the code is full of $_GET["this"] and $_POST["that"]. I have always used the more phpish $this->_request->getPost('this') and $this->_request->getQuery('that') (this one being not so much logical with the getquery insteado of getGet).

So i was wondering if my method was safer/better/easier to mantain. I read in the Zend Framework documentation that you must validate your own input since the request object wont do it.

That leaves me with 2 questions:

  • What is best of this two? (or if theres another better way)
  • What is the best practice for validating php input with this methods?

Thanks!

like image 733
DFectuoso Avatar asked Jan 19 '09 16:01

DFectuoso


2 Answers

I usually use $this->_request->getParams(); to retrieve either the post or the URL parameters. Then I use the Zend_Filter_Input to do validation and filtering. The getParams() does not do validation.

Using the Zend_Filter_Input you can do application level validation, using the Zend Validators (or you can write your own too). For example, you can make sure the 'months' field is a number:

$data = $this->_request->getParams();  $validators = array(     'month'   => 'Digits', );  $input = new Zend_Filter_Input($filters, $validators, $data); 
like image 95
Brian Fisher Avatar answered Sep 19 '22 08:09

Brian Fisher


Extending Brian's answer.

As you noted you can also check out $this->_request->getPost() and $this->_request->getQuery(). If you generalize on getParams(), it's sort of like using the $_REQUEST superglobal and I don't think that's acceptable in terms of security.

Additional to Zend_Filter, you may also use simple PHP to cast the required.

E.g.:

$id = (int) $this->_request->getQuery('id'); 

For other values, it gets more complicated, so make sure to e.g. quote in your DB queries (Zend_Db, see quoting identifiers, $db->quoteIdentifier()) and in views use $this->escape($var); to escape content.

like image 25
Till Avatar answered Sep 23 '22 08:09

Till