如何在Zend Framework 2视图中自动转义变量

时间:2012-09-09 18:59:59

标签: security view escaping zend-framework2

很多时候,在Zend Framework 2视图中,我将调用$this->escapeHtml()来确保我的数据是安全的。有没有办法将此行为从黑名单切换到白名单?

PS:阅读Padraic Brady的一篇文章,其中提到automatic escaping is a bad idea。额外的想法?

2 个答案:

答案 0 :(得分:4)

您可以编写自己的ViewModel类,在将变量分配给它时会转义数据。

答案 1 :(得分:1)

感谢Robs评论,我扩展了ZF2 ViewModel,如下所示:

namespace Application\View\Model;

use Zend\View\Model\ViewModel;
use Zend\View\Helper\EscapeHtml;

class EscapeViewModel extends ViewModel
{
/**
 * @var Zend\View\Helper\EscapeHtml
 */
protected $escaper = null;

/**
 * Proxy to set auto-escape option
 *
 * @param  bool $autoEscape
 * @return ViewModel
 */
public function autoEscape($autoEscape = true)
{
    $this->options['auto_escape'] = (bool) $autoEscape;
    return $this;
}

/**
 * Property overloading: get variable value;
 * auto-escape if auto-escape option is set
 *
 * @param  string $name
 * @return mixed
 */
public function __get($name)
{
    if (!$this->__isset($name)) {
        return;
    }

    $variables = $this->getVariables();
    if($this->getOption('auto_escape'))
        return $this->getEscaper()->escape($variables[$name]);
    return $variables[$name];
}


/**
 * Get instance of Escaper
 *
 * @return Zend\View\Helper\EscapeHtml
 */
public function getEscaper()
{
    if (null === $this->escaper) {
        $this->escaper = new EscapeHtml;
    }

    return $this->escaper;
}
}

在Controller中,它可以像这样使用:

public function fooAction()
{
    return new EscapeViewModel(array(
        'foo' => '<i>bar</i>'
    ));

    //Turn off auto-escaping:
    return new EscapeViewModel(array(
        'foo' => '<i>bar</i>'
    ),['auto_escape' => false]);
}

<强>问题: 如果soemebody会评论,如果这是最好的做法,或者如果有更好的和ecp,我将不胜感激。更有效率和资源节约的方式?