About Html::encode() - Why and When?

Hello,

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.

Thank you,

Ben

Look at:

http://www.yiiframework.com/doc-2.0/guide-helper-html.html

Endcoding and Decoding.

And read about html special chars:

http://php.net/manual/en/function.htmlspecialchars.php

For short:

With encode you ensure that your string is converted into proper html… Take the German Letter Ö for example encoded in html it is ö

Regards

Thank you so much for the links and explanations, I understand better now.

So really you better use it each time you output html from the database onto a view if I understood.

I am wondering if everyone does it.

I don’t know if everyone does it all the time.

But I do it everytime I output strings / text.

Regards

Thanks Meta:-)

Let me clarify things a bit.

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: &lt;span&gt;text&lt;/span&gt;



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:-)

You’re welcome.

Please, reload the page, I added some new bits to my post.

Thanks!

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 :slight_smile: . stay safe on Yii and stay safe at home!