How to allow code in htmlpurifier

2019-03-06 02:38发布

问题:

I am in the middle of creating a comment box where people can ask their questions.

I get a lot of people asking how do they do something which involves inputting code into the form.

The form goes through htmlpurifier to make sure its safe to use.

But when ever someone inputs echo codes etc it does not allow it. Or if someone inputs a div then it does not allow that either, even when wrapping in the < code >.

For instance this:

<code><div class="classname"></div></code>

will just add a div.

and

<code><?php echo $word; ?></code>

Will not show the code at all.

The way I have set this up the htmlpurifier is:

$content    = $_POST['comment'];

$rawf   =  str_replace('<code>', '<pre><code>', $content);
$rawfp  =  str_replace('</code>', '</code></pre>', $rawf);

require_once '../Libs/htmlPurifier/library/HTMLPurifier.auto.php';

$purifierconfig = HTMLPurifier_Config::createDefault();

$purifierconfig->set('HTML.Allowed', 'b,a[href],i,em,br,code,pre');

$purifier   = new HTMLPurifier($purifierconfig);
$clean_html = $purifier->purify($rawfp);
$ticketpost =  str_replace('<a ', '<a rel="nofollow" ', $clean_html);

Then the $ticketpost is inserted into the database using PDO prepared statements.

Is there something I am not doing, or doing wrong?

If so please could you help.

Thanks

回答1:

Your problem is, if the input is truly HTML, then any code fragments need to be escaped in order to show up in the result. We have special <![CDATA[ put code here ]]> syntax for just that, but sometimes, you don't want to bother users with extra syntax like that. In that case, you could do a preg_replace_callback on code tags, where the callback escapes the code between two code tags. But notice, now, there is no way to express a code fragment that contains code tags! So it is all tradeoffs.