如何清理可能包含一些 HTML 标签(如 <b><i><u> 但不包含 <script> 标签和编码脚本的字符串以避免 xss

how to sanitise string that may contain some HTML tags like <b><i><u> but not contain <script> tag and encoded scripts to avoid xss

我想清理 html 但我想保留

这样的标签
<b> </b>
<i> </i>
<u> </u>
<code> </code>

但我想删除像

这样的标签
<script></script>

和编码不安全html像

<IMG SRC=X ONERROR="&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041">

如何在不使用库的情况下做到这一点。

//allow the tags you want to keep

$ALLOWED_TAGS = '<p><h1><h2><h3><h4>';


//strip_tags function will remove the tags that you don't need

echo strip_tags('Hello <b><i>world!</i></b>', $ALLOWED_TAGS);

我建议您删除所有标签。 将允许的标签设置为不同的容器,即:[b]粗体[/b],稍后用允许的标签替换它们,这将帮助您避免用户可能发送的不需要的 HTML 属性。

xss 清理

为 HTML 输出消毒

function h($string) {
    return htmlspecialchars($string);
}

为 JavaScript 输出消毒

function j($string) {
    return json_encode($string);
}

消毒以用于 URL

function u($string) {
    return urlencode($string);
}

用法

echo h("<h1>string from database</h1><br />");

strip_tags我用来描述。

$allowed_tags = '<div><a><href><br><p><span><img>';
echo strip_tags($row->description, $allowed_tags);