如何使用 PHP 在白名单中允许 HTML

2021-12-23 00:00:00 filter php sanitization

我知道多年来有很多关于使用 PHP 过滤数据的最佳方法的讨论,但我想在我当前的项目中采用白名单方法.

我只希望用户能够使用以下 HTML

粗体<i>斜体</i><u>下划线</u><s>删除线</s><大>大尺寸</大><小>小尺寸</小>超链接<a href="http://www.site.com">网站</a>项目符号列表:<ul><li>一个项目</li><li>另一个项目</li>有序列表:<ol><li>第一项<li>第二项</ol><blockquote>因为它是缩进的</blockquote><h1>标题 1</h1><h2>标题2</h2><h3>标题3</h3>

任何人都可以向我展示在 PHP 中执行此操作的最佳方法吗?我过去只允许所有 html 减去某些代码

解决方案

最简单的解决方案是 strip_tags(), 它接受包含允许标签的第二个参数:

strip_tags($string, "

I know there is a lot of discussion for years on best methods of filtering data with PHP but I would like to go the whitelist approach in my current project.

I only want a user to be able to use the following HTML

<b>bold</b>
<i>italics</i>
<u>underline</u>
<s>strikethrough</s>
<big>Big size</big >
<small>Small size</small>

Hyperlink <a href="http://www.site.com">website</a>

A Bulleted List:
<ul>
<li>One Item</li>
<li>Another Item</li>
</ul>

An Ordered List:
<ol>
<li> First Item</li>
<li> Second Item</li>
</ol>

<blockquote>Because it is indented</blockquote>

<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>

Can anyone show me the best method of doing this for performance in PHP? I have only in the past allowed all html minus certain codes

解决方案

The simplest solution would be strip_tags(), which accepts a second argument containing allowable tags:

strip_tags($string, "<b><i><u><a><s><big><small><ul><li><ol><blockquote><h1><h2><h3>");

相关文章