Search code examples
phphtmlpurifier

HTMLPurifier strips select tags


I am using HTMLPurifier to prevent xss. The html contains all sort of tags for example SELECT, OPTION. But HTMLPurifier removes SELECT, OPTION tags and keeps plain text. How can I allow SELECT, OPTION tags.

Here is the code

$html = "<select>
       <option value="1" selected>Test 1</option>
       <option value="2" selected>Test 2</option>
</select>";

$config = \HTMLPurifier_Config::createDefault();
$config->set( 'AutoFormat.RemoveEmpty', true );
$purifier = new \HTMLPurifier( $config );
$cleanHtml = $purifier->purify( $dirtyHTML );

The code return 'Test 1Test 2'


Solution

  • <select> and <option> are form elements. Since forms can make phishing trivial, HTML Purifier, with its "secure by default" mindset, does not even bother to load up the HTML definition of forms, so you can't simply enable forms by (only) setting HTML.AllowedElements.

    However, the setting HTML.Trusted lets you enable forms, but that enables them altogether. For some discussion on altering the behaviour, see the thread "Anyone have a config that allows form elements?" on the HTML Purifier discussion forum, e.g.:

    The forms would only be allowed to have an empty action; they always submit to themselves.

    Not by default: you'd have to code that.

    How would I enable it?

    Probably the easiest thing to do is to copy-paste the definitions from HTMLPurifier/HTMLModule/Forms.php and then tweaking them as appropriate. Note that these definitions assume trusted users, so please please please check all of the fields you allow carefully.