How to allow code in htmlpurifier

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-02 17:04:12

问题


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.



来源:https://stackoverflow.com/questions/16326121/how-to-allow-code-in-htmlpurifier

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!