decoding html entities in an array of strings

Hello everyone.

As we know it’s very useful (for security reasons) to convert special characters to html entities when we want to store data in a database.

For this purpose in Yii we have CHtml::encode() function for a single string and CHtml::encodeArray() for an array of strings.

So in my controller I have this code


$model = new Books;

$model->attributes=CHtml::encodeArray($_POST['Books']);

$model->save()

This works great. But now if I want to load the data from my database into my form for editing the strings remain encoded, that is my single quote for example is shown as


& #039;

in my textField. This is not good.

Unfortunately we don’t have corresponding CHtml::decodeArray() function. So I desided to slightly change CHtml::encodeArray() and got this


private function decodeArray($data)

	{

	    $d=array();

	    foreach($data as $key=>$value)

	    {

		if(is_string($key))

		    $key=htmlspecialchars_decode($key,ENT_QUOTES);

		if(is_string($value))

		    $value=htmlspecialchars_decode($value,ENT_QUOTES);

		else if(is_array($value))

		    $value=self::decodeArray($value);

		$d[$key]=$value;

	    }

	    return $d;

	}

Now to load my data to my form for editing I desinged a little trick. Here it is


public function actionKedit()

{

     ...

     $model = Books::model()->findByPk($_GET['id']);

     $model_dec = new Books;

     $model_dec->attributes=$this->decodeArray($model);

     $this->render('kedit',array('model'=>$model_dec));

     ...

}

It works, but I’d like to know if it’s a right solution or is there a better, more effective way to assign to $model->attributes the array of decoded strings?

Thanks.

You are a bit misusing htmlEncode.

In database data should be saved as they are, there are not security problem (addSlashes is requred, but is authomatically used by all function that writes/ search in database).

You should htmlEncode all userinput that will be sended in pages, for avoind javascript injection.

Many functions and widget (chtml::label, for example) authomatically encode. Therefore you see the text encoded, because has been encoded 2 times.

The solution is not encode when you save in database (it will make the data hard to read from phpmyadmin, e.g) but only when you use userinput in pages.

That’s exactly what I do. I use


$model->attributes=CHtml::encodeArray($_POST['Books']);

to store data in my database from user input on my page. But how in this case can I save the data unencoded?