Use Sanitize::html() class in the views

Update (9/16/2008): As some people pointed out it’s easier to use the h() method defined in basics.php of the core, it achieves the same basic goal, but since Sanitize class has other methods and purposes, I’m gong to leave this as an informational example and food for thought. (i.e. you could completely strip-out all dangerous characters using Sanitize for one view, while keeping the data intact for other views and in the DB).

A little example for when Sanitize::html() can be quite useful in a view of your application…

Perhaps you have some Comments form, where you wouldn’t mind if users entered something like:

[sourcecode language=”javascript”]

[/cc]

(Maybe it was for educational purposes only…)

Of course the common rule is to make your data safe before you save it. However, such data is perfectly fine for saving, but very dangerous for displaying back to the user. Therefore you don’t want to convert any HTML entities (i.e. ‘<') to their safe alternatives, before it goes into the DB. In the view, all you need is to call App::import(‘Sanitize’); then, you can easily do something like:

echo Sanitize::html($comment['Comment']['body']);
%d bloggers like this: