save html in database securely

Hi

I want your opinion for storing to database and display a html/text submiting by a user

I want to be secure both of the database and display to other users

Thanks

just use htmlpurifier to filter out possible XSS injections… if possible try to avoid extensive HTMLand use bbcode or sth like it and escape other html chars, or create own restrictive htmlpurifier configuration and use it during data saving

Check this , should do the job:

http://www.yiiframework.com/doc/api/1.1/CHtmlPurifier

Hi redguy and thanks for the fast response!

Do you have a real example ?

I want to preserve most of html tags (without javascript).

(is it save to save any html tag in database or is better to use CHtml::encode just before save it to database?)

for example


$post->text = CHtml::encode($post->text); 

$post->save();

or it is better


$purifier = new CHtmlPurifier();

$post->text = $purifier->purify($post->text);

$post->text = CHtml::encode($post->text); 

$post->save();

and then use it for display without encode


echo $post->text; //is already encoded! (from database)

The text is derived from html editor

Thanks! :)

Hi zivkovic, I would like secure both for the other user and the database

I would go with




$purifier = new CHtmlPurifier();

$post->text = $purifier->purify($post->text);

$post->save();



as encoding is probably not what you want - if you allow user to enter HTML you probably want to show it as html without escaping special chars. Anyway - you can always encode it just before showing (even in view) and most Yii widgets do it by default

Thank you for sharing your opinion by a vote :)


	

public function rules()

{

	return array(

	array('myattribute','filter','filter'=>array($obj=new CHtmlPurifier(),'purify')),

	);

}

this will remove any malicious script

Thanks all of you for your opinions!

either use it in rules as filter or use beforeValidate in any case use only CHtmlPurifier :)

I would say use the HTMLpurify to clean the database before you save it and encode it when you display it if you need to, don’t use HTMLpurify to display it, it has little extra overhead.