Recently, I noticed that many sites made on the Yii Framework have the same error:
If you add square brackets in some input field in the name attribute and submit the form, you can get an error message, like:
htmlspecialchars() expects parameter 1 to be string, array given
Sometimes you can even see the source code of PHP files, if the developer forgot to remove the constant YII_DEBUG.
This error is also present on large projects and even on
yiiframework.com/search/?q%5b%5d=It occurs due to the fact that the standard validation rules generated by Gii only protect against attempts to write incorrect data in the database. When outputting user data to a page,
CHtml::encode()
usually used, but it passes the variable directly to the PHP function
htmlspecialchars()
and does not check its type.
One way to solve this problem is to write a small behavior:
class FilterArraysBehavior extends CModelBehavior { public function filterArrays($value) { is_array($value) && $value = null; return $value; } public function beforeValidate($event) { $validator = new CFilterValidator(); $validator->attributes = array_keys($this->owner->attributes); $validator->filter = array($this, 'filterArrays'); $this->owner->validatorList->add($validator); } }
This behavior adds a filtering validation rule for all attributes of the model.
It can be connected immediately to all models, if you change their common ancestors:
protected/components/Model.php
and
protected/components/FormModel.php
adding the following code:
public function init() { $this->attachBehavior('FilterArraysBehavior', 'behaviors.FilterArraysBehavior'); }
After that, the arrays transmitted by the user will be converted to empty lines on the output.