For example, if your website has comments, an attacker may add the following text as a comment:
alert('Hello from a hacker');
To avoid that, it is recommended to properly encode the output.
In Yii2 (our favorite framework), it is quite easy to do that.
If you’re sure you’ll have just text in your data, you can escape it in the view with
Html::encode() while outputting it:
php echo Html::encode($post);
If you need to output HTML anyway
In case you need to output HTML entered by user it’s getting a bit more complicated. Yii has a built in HtmlPurifier helper which cleans up everything dangerous from HTML. In a view you may use it as the following:
Note: HtmlPurifier isn’t fast so consider caching what’s produced by
HtmlPurifiernot to call it too often.