Yii 2.0 XSS filtering

Yii 2.0 XSS filtering

In this article I want to talk about XSS filtering in Yii 2.0. What is XSS? XSS or cross-site scripting happens whenoutput isn't escaped properly when outputting HTML to the browser.


In this article I want to talk about XSS filtering in Yii 2.0.

What is XSS?

XSS or cross-site scripting happens when output isn't escaped properly when outputting HTML to the browser. For example, if user instead of entering a title for a page, enters <script>alert("Hi!");</script>, when outputting title of the page an alert box will pop up in your browser! This can be very dangerous based on things people can do using XSS.

How to avoid XSS?

To avoid XSS you need to output the text in one of the following formats:

  1. Output as plain text
  2. Output as HTML

If you need to output your text as plain text, you have to do the following:

<?php \yii\helpers\Html::encode($text) ?>

And if you need to output your text as HTML, you have to do the following:

<?php \yii\helpers\HtmlPurifier::process($text) ?>