1

I'm using Yii as PHP Framework and when I need to display some information from database, I'm always using CHtml::encode to improve security.

My question is: Do I need to do the same when I display values at Yii widgets, such as TbDetailView or TbGridView?

For example, is the CHtml::encode necessary at the code below?

<?php $this->widget('bootstrap.widgets.TbDetailView',array(
'data'=>$model,
'attributes'=>array(
    'id',
    'nome',
    'descricao',
    'origem',
            array('label'=>'Tipo de Refeição', 'value'=>CHtml::encode($model->tipoRefeicao ? $model->tipoRefeicao->nome : '')),
            array('label'=>'Ativo', 'value'=>CHtml::encode($model->ativo ? 'Sim' : 'Não')),
),
)); ?>

1 Answers1

1

The CHtml::encode() function is wrapper for PHP htmlspecialchars function it encodes special characters into HTML entities. certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings, conversion performed are

 - '&' (ampersand) becomes '&amp;'
 - '"' (double quote) becomes '&quot;' 
 - "'" (single quote) becomes '&#039;'   
 - '<' (less than) becomes '&lt;'    
 - '>' (greater than) becomes '&gt;'

Meaning if that field in DB is likely to have any of these characters you will have to encode it, otherwise it might break the HTML output, if it will not, then there is no need to encode it

Manquer
  • 7,390
  • 8
  • 42
  • 69
  • @manquer, so essentially you are saying if you cannot trust the information, then encode it. – crafter Jun 26 '14 at 09:40
  • "trust" implies it is secure, encoding does not protect you against XSS or similar attacks. I would rather say if you cannot control/limit the user input then encode, for example you allow html formatting in a textarea like say this comment box. then you have to encode it before it is shown in the UI. Otherwise if I add two closing divs like this as part of the comment it will completely screw up the layout – Manquer Jun 26 '14 at 10:05
  • could you please give a direction what can protect from XSS then? I though it really helped because inseting – Tebe Aug 18 '17 at 21:30