3

这是交易,我正在制作一个项目来帮助向人们教授 HTML。当然,我害怕那个渣男史蒂夫(见图 1)。

所以我想阻止所有HTML 标签,除了那些在非常具体的白名单上批准的标签。

在那些批准的 HTML 标记中,我也想删除有害的属性。比如onloadonmouseover。另外,根据白名单

我想过正则表达式,但我很确定它是邪恶的,对工作没有多大帮助。

谁能给我一个正确的方向?

提前致谢。


图。1。

渣男史蒂夫

4

3 回答 3

5
require_once 'library/HTMLPurifier.auto.php';

$config = HTMLPurifier_Config::createDefault();

 // this one is needed cause otherwise stuff 
 // considered harmful like input's will automatically be deleted
$config->set('HTML.Trusted', true);

// this line say that only input, p, div will be accepted
$config->set('HTML.AllowedElements', 'input,p,div');

// set attributes for each tag
$config->set('HTML.AllowedAttributes', 'input.type,input.name,p.id,div.style');

// more extensive way of manage attribute and elements... see the docs
// http://htmlpurifier.org/live/configdoc/plain.html
$def = $config->getHTMLDefinition(true);

$def->addAttribute('input', 'type', 'Enum#text');
$def->addAttribute('input', 'name', 'Text');

// call...
$purifier = new HTMLPurifier($config);

// display...
$html = $purifier->purify($raw_html);
  • 注意:正如您所要求的,此代码将作为白名单运行,仅接受输入、p 和 div,并且仅接受某些属性。
于 2012-03-28T21:06:28.077 回答
1

使用Zend 框架 2 条带标签。下面的示例接受 ul、li、p... 和 img(仅具有 src 属性)和链接(仅具有 href 属性)。其他一切都会被剥夺。如果我没记错的话 zf1 会做同样的事情

     $filter = new \Zend\Filter\StripTags(array(
        'allowTags'   => array(
            'ul'=>array(), 
            'li'=>array(), 
            'p'=>array(), 
            'br'=>array(), 
            'img'=>array('src'), 
            'a'=>array('href')
         ),
        'allowAttribs'  => array(),
        'allowComments' => false)
    );

    $value = $filter->filter($value);
于 2012-10-26T17:56:46.870 回答
0

对于标签,您可以使用strip_tags

有关属性,请参阅如何从 html 标记中删除属性?

于 2012-03-27T20:35:27.930 回答