Search code examples
phphtmlsecuritysanitizationhtmlpurifier

HTMLPurifier : How to allow a single attribute without redefining the whole whitelist


I'm using HTMLPurifier to sanitize HTML string (it's about security).

Some attributes (like width or height) are removed when HTMLPurifier is called. I don't consider this as a security issue.

How can I add this attribute without redefining the whitelist ?

I searched on Stackoverflow and HTMLPurifier documentation, but the only solution seems to be :

$config->set('HTML.Allowed', 'p,b,a[href],i');

But this is not a solution, because I don't want to redefine the whitelist (I trust the default HTMLPurifier configuration, I just want to add an exception).


Solution

  • This code:

    <?php
    
    require('purifier/library/HTMLPurifier.auto.php');
    
    $html = "<img width='200' height='200' src='test.jpg' alt='bla>";
    $config = HTMLPurifier_Config::createDefault();
    $purifier = new HTMLPurifier($config);
    echo $purifier->purify($html) . "\n";
    
    $html = "<table width='100'><tr><td>test</td></tr></table>";
    echo $purifier->purify($html) . "\n";
    
    ?>
    

    Produces this output:

    <img width="200" height="200" src="test.jpg" alt="bla" />
    <table width="100"><tr><td>test</td></tr></table>
    

    Using php 5.3.10 and HTMLPurifier version 4.4.0. So these attributes are not stripped by default (I am using a clean install of HTMLPurifier)

    On which HTML elements are you using the width/height attributes?

    Also note invalid attributes will be stripped when using xhtml strict. Width and height on img and table elements are allowed as far as I know but should be lowercase. Except for "width='100%'" on an image element (added for completeness after rap-2-h his comment)

    In general: use addAttribute instead of the whitelist to add allowed attributes.