Can't make CHtmlPurifier work :(

Hi Yiivers :)

I’m new to Yii and working on my first project. I got a problem with CHtmlPurifier : it seems not to be filtering anything. I’m sure I missed something obvious.

Here is my code :

$badlink = "javascript:alert('hello');";

$p = new CHtmlPurifier();

$p->options = array('URI.AllowedSchemes'=>array(

			  'http' => true,

			  'https' => true));


$link = $p->purify($badlink);


The result is the exact same badlink :

string(26) "javascript:alert('hello');"

Trying with ftp and other URI schemes also does not work.

It seems CHtmlPurifier is just not there but if I do a var_dump of $p object, it’s there :

object(CHtmlPurifier)#25 (10) { ["options"]=> array(1) { ["URI.AllowedSchemes"]=> array(2) { ["http"]=> bool(true) ["https"]=> bool(true) } }

Any idea ?

Thanks !


The value “javascript:alert(‘hello’);” is a plain string (from the view of CHtmlPurifier), not HTML and CHtmlPurifier has nothing to do with plain strings. Try this:

$html = '<script type="text/javascript">alert("hello");</script>';


and you will see CHtmlPurifier in work.

Ah yes, indeed, it’s filtering the tags all right ! I believed that the URI.AllowedSchemes statement would prevent other schemes being used. So if I want to make sure nothing but http or https URLs are accepted, I need to use another method ?

Thanks !


Pass the whole html element to the purify() method:

$p->purify('<a href="javascript:alert(\'hello\');">link text</a>');

Not tested, but it should work.

EDIT: and of course don’t forget to enable <a> element and “href” attribute in the purifier config.

Ahh I see ! In fact I may not be using the right tool for the job, then. The URL is sent through POST and comes from another script that grabs it as a URL, not a link. I’m just trying to avoid someone crafting a POST request and getting in a poisoned URL. But there is no HTML element per se. My mistake !

Thanks again !