Quick question, shall I use Html::encode only on views that are public or on all view which are for both logged in and guest users?
I am not understanding perfectly why it is necessary to use the encode function, could someone give me a bit more details on this please with(if you can) a real life example of what could happen if the function is not being used.
Html::encode() is needed for places where one expects plain text, not HTML. It will render any HTML tags from input literally. Example:
$text = '<span>some text</span>';
echo Html::encode($text);
// or like this
echo Yii::$app->formatter->asText($text);
// output: <span>text</span>
It is a good practice to use Html::encode on every piece of textual data that originates from the DB or any third party service. In fact, core widgets like GridView and DetailView do this kind of encoding automatically, unless you override format of a field.
On the other hand, if you need to render the data as HTML, your should use HtmlPurifier:
echo HtmlPurifier::process($html);
// or like this
echo Yii::$app->formatter->asHtml($html);
HtmlPurifier strips off some types of "unsafe" markup, so you might need to alter its configuration. In fact, core widgets like GridView and DetailView do this kind of processing, if you set format of a field to "html".
Thank you so much for the exaplanation "In fact, core widgets like GridView and DetailView do this kind of encoding automatically, unless you override format of a field.", this was very good to know:-)
If you don’t use Html::encode AFAIK you are vulnerable to attacks; anybody can post a comment for example with content
<script*
alert("Hi i hacked your website. give me 1 million dollars. transfer the money to me on 123456789. have fun >:) ");
//Some bad stuff to redirect you, edit page contents, steal data etc…
</script*
* is > but couldn't post it here x)
That’s it when you load the page the script will run. always use Html::encode to be safe from these attacks. I have just hacked myself so thought of sharing my experience . stay safe on Yii and stay safe at home!