PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Escaping Output

One of the most important tasks to perform in a view script is to make sure that output is escaped properly; among other things, this helps to avoid cross-site scripting attacks. Unless you are using a function, method, or helper that does escaping on its own, you should always escape variables when you output them.

Zend_View comes with a method called escape() that does such escaping for you.

<?php
// bad view-script practice:
echo $this->variable;

// good view-script practice:
echo $this->escape($this->variable);

By default, the escape() method uses the PHP htmlspecialchars() function for escaping. However, depending on your environment, you may wish for escaping to occur in a different way. Use the setEscape() method at the controller level to tell Zend_View what escaping callback to use.

<?php
// create a Zend_View instance
$view = new Zend_View();

// tell it to use htmlentities as the escaping callback
$view->setEscape('htmlentities');

// or tell it to use a static class method as the callback
$view->setEscape(array('SomeClass''methodName'));

// or even an instance method
$obj = new SomeClass();
$view->setEscape(array($obj'methodName'));

// and then render your view
echo $view->render(...);

The callback function or method should take the value to be escaped as its first parameter, and all other parameters should be optional.

Zend Framework