简体   繁体   中英

How to prevent XSS with ZF2?

Need to escape this line before rendering it in HTML:

$this->view->zipcode = $this->getRequest()->getParam('zipcode','');

I didn't work with ZF2 before, I want to properly escape this line to protect my site against XSS.

I don't know how to use correctly escape() , htmlspecialchars() , and others in Zend Framework 2.

There are tons of questions on how to use escape HTML, and using htmlspecialchars() isn't exactly rocket science, but since you are scoping this to ZF2, let's try to make this useful.

ZF2 includes the Escaper class exactly for this situation.

It's easy enough to use it:

$escaper             = new Zend\Escaper\Escaper('utf-8');
$unsafe_input        = $this->getRequest()->getParam('zipcode','');
$safe_output         = $escaper->escapeHtml($unsafe_input);
$this->view->zipcode = $safe_output;

The class has also specific methods to deal with JS, CSS, URLs, and HTML attributes. Also, be aware than the parameter you pass to the Escaper constructor should match the character encoding of the page you are rendering. UTF-8 is mostly a safe bet nowadays, but other encoding like 'ISO-8859-1' are not uncommon.

As some people have said in comments, you can also do the escaping directly on the view using the built-in helper. The view should either be aware of what data might come from user input, or you just escape every variable you are going to output:

So in your view, following your example, you'd do:

 $this->escapeHtml($this->zipcode);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM