Request class with auto-sanitization

I will show you here a Request class, which extends the Zend_Controller_Request_Http and also does a basic xss sanitization(automatically, so you will never miss anything)! I know, it’s a poor example, I have a lot of ideas of writing a better one, using Zend_Filter_Input and the Zend_View object. This is an example ONLY to show you, that I like to do sanitizations AUTOMATICALLY so I never miss any input variables.

class ZendExt_Request extends Zend_Controller_Request_Http{

/**
* Retrieve an ESCAPED parameter
*
* Retrieves an ESCAPED parameter from the instance. Priority is in the order of
* userland parameters (see {@link setParam()}), $_GET, $_POST. If a
* parameter matching the $key is not found, null is returned.
*
* If the $key is an alias, the actual key aliased will be used.
*
* @param mixed $key
* @param mixed $default Default value to use if key not found
* @return mixed
*/
public function getParam($key, $default = null){

$value = parent::getParam($key,$default);

if(is_string($value))
return htmlentities($value,ENT_QUOTES,'UTF-8');
else
return $value;

}

/**
* Retrieve an array of ESCAPED parameters
*
* Retrieves a merged array of parameters, with precedence of userland
* params (see {@link setParam()}), $_GET, $POST (i.e., values in the
* userland params will take precedence over all others).
*
* @return array
*/
public function getParams(){
$values = parent::getParams();

foreach($values as $k=>$v){
if(is_string($v))
$values[$k] = htmlentities($v,ENT_QUOTES,'UTF-8');
}

return $values;

}

}

You set this this class in your front controller like this:
$front->setRequest(‘Zend_Controller_Request_Http’);
Next everytime in your controllers you will use
$this->_getParam(‘some_variable’), and then assign the variable to the $this->view object, you can echo it in the view script, without using $this->escape(….). Code example:
Before:

In controller:
$variable = $this->_getParam('variable');
$this->view->variable = $variable;

In the view script
<?=$this->escape($this->variable)?>

After:
In controller:
$variable = $this->_getParam('variable');
$this->view->variable = $variable;

In the view script
<?=$this->variable?>

AUTOMATICALLY is the keyword here!

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.