HTMLPurifier by default allows a lot of tags that I don't want to allow. According to the documentation you have to add definitions like this:

$config = HTMLPurifier_Config::createDefault();
if ($def = $config->maybeGetRawHTMLDefinition()) {
    $def->addAttribute('a', 'target', new HTMLPurifier_AttrDef_Enum(array('_blank','_self','_target','_top')));
}
$purifier = new HTMLPurifier($config);

The problem is that I can't find a way to remove all tags that comes from HTMLPurifier_Config::createDefault();.

For example the HTML <div>Sometext</div> will keep the DIV tag using the above initialization code.

How can I set HTMLPurifier to only allow <strong>, <a href="*"> and <p>?

有帮助吗?

解决方案

You say: "According to the documentation you have to add definitions like this".

Unless something fundamental has changed since the last time I checked the library (a year ago, about), that's not quite true - that part exists for if you want to teach HTML Purifier new attributes that it isn't natively aware of. For example, if you wanted to teach your HTML Purifier to accept non-standard <font> attributes, like align="", you'd need to alter the raw HTML definition.

However, if your whitelist consists purely of regular HTML elements (and yours does!), you just need to use the $config object:

$config = HTMLPurifier_Config::createDefault();
$config->set('HTML.AllowedElements', array(
    'strong','a','p'
));
$config->set('HTML.AllowedAttributes', array(
    'a.href'
));
$purifier = new HTMLPurifier($config);

That should work. Are you running into problems with that constellation?

(Check out this document, too: http://htmlpurifier.org/live/INSTALL )

其他提示

The solution I found was to use the old way of configuring HTMLPurifier;

if($def = $config->maybeGetRawHTMLDefinition()) {
    $config->set('HTML.AllowedElements', array(
        'strong','a','p'
    ));
    $config->set('HTML.AllowedAttributes', array(
        'a.href'
    ));
}

How this works in relation with the HTMLDefinition I don't know. Maybe they have a compatability layer.

The biggest concern I have is that this is not using the $def variable returned - and that the changes I do to the config is not cached.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top