【问题标题】:Remove certain tags from html input with PHP使用 PHP 从 html 输入中删除某些标签
【发布时间】:2016-11-23 03:47:53
【问题描述】:

我有一个表单,用户可以在其中使用 html 设置自己的输入样式。我想用 PHP 清理服务器端的输入。但是,我想确保所有输入都是安全的并且符合我想要的。我已经有了 XSS 保护,所以这不是要删除脚本。

当用户提供输入时,我想删除pimgahrbrtbodytrtd、@987654329 以外的标签@、ulollispan(基本上是除 div 之外的所有文本格式)。我想删除除<a>href<img>src<p>style 以外的任何属性。对于<p> 样式,我只想保留以下属性:

  • color
  • background-color
  • line-height
  • text- 开头的任何内容

此外,我希望能够将文本裁剪到一定长度,同时保留结束标签并确保每个开始标签也有一个结束标签。

例如,Stack Overflow 编辑器如何在保存输入并将其显示给用户之前对其进行解析和清理?

谢谢。

【问题讨论】:

  • 我不知道 SO 编辑器背后的代码。如果您向我们展示您的代码,也许我们可以帮助您改进它。
  • 我的代码来自 Summernote 编辑器。澄清一下,这是关于后端的。
  • 你在用 CKEditor 吗?

标签: php html parsing dom sanitization


【解决方案1】:

我使用http://htmlpurifier.org/ 来清理 html 输入。您可以定义允许的标签、属性和样式。我添加了我项目中的代码作为示例。

    $configuration = HTMLPurifier_Config::createDefault();
    $configuration->set('Attr.EnableID', true);
    $configuration->set('AutoFormat.RemoveEmpty', true);
    $configuration->set('AutoFormat.RemoveEmpty.RemoveNbsp', true);
    $configuration->set('HTML.AllowedAttributes', array('span.style', '*.id', '*.src', 'a.href', 'table.style', 'img.style', 'td.colspan', 'td.rowspan', 'td.style'));
    $styles = array('margin-left', 'color', 'background-color', 'text-decoration', 'font-weight', 'font-style', 'border', 'border-collapse', 'height');
    $configuration->set('CSS.AllowedProperties', $styles);
    $htmlPurifier = new HTMLPurifier($configuration);
    return $htmlPurifier->purify($html);

【讨论】:

  • 太棒了。我实际上一直在使用它来通过自动配置来净化脚本,但我不知道它可以做到这一切。谢谢。
猜你喜欢
  • 2013-08-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-03
  • 2019-01-06
  • 2019-11-29
  • 1970-01-01
  • 2018-01-03
  • 2011-11-20
相关资源
最近更新 更多