php多种方法实现xss过滤
1. 使用 htmlspecialchars() 函数
htmlspecialchars() 是一个PHP内置函数,用于将特殊字符转换为HTML实体,从而防止浏览器将其解释为HTML或脚本代码。
<?phpfunction sanitizeInput($input) {// 将特殊字符转换为HTML实体return htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
}// 示例
$userInput = '<script>alert("XSS")</script>';
$safeInput = sanitizeInput($userInput);echo "Sanitized Input: " . $safeInput;
// 输出: Sanitized Input: <script>alert("XSS")</script>?>
2. 使用 htmlentities() 函数
htmlentities() 类似于 htmlspecialchars(),但会将所有适用的字符转换为HTML实体。
<?phpfunction sanitizeInputWithEntities($input) {return htmlentities($input, ENT_QUOTES, 'UTF-8');
}// 示例
$userInput = '<img src=x onerror=alert("XSS")>';
$safeInput = sanitizeInputWithEntities($userInput);echo "Sanitized Input: " . $safeInput;
// 输出: Sanitized Input: <img src=x onerror=alert("XSS")>?>
3. 自定义过滤函数
在某些情况下,你可能需要自定义过滤逻辑,例如只允许特定的HTML标签或属性。以下是一个简单的示例,只允许<b>
和<i>
标签:
<?phpfunction customSanitize($input) {// 允许 <b> 和 <i> 标签return strip_tags($input, '<b><i>');
}// 示例
$userInput = '<b>Bold</b> <script>alert("XSS")</script> <i>Italic</i>';
$safeInput = customSanitize($userInput);echo "Custom Sanitized Input: " . $safeInput;
// 输出: Custom Sanitized Input: <b>Bold</b> <i>Italic</i>?>
4. 内容安全策略(CSP)
除了过滤输入,还可以通过设置内容安全策略(CSP)来减轻XSS攻击的影响。CSP是一种浏览器安全机制,通过HTTP头来限制资源加载和执行。
<?php// 在PHP中设置CSP头
header("Content-Security-Policy: default-src 'self'; script-src 'self';");?>
我的个人PHP项目:
PHP全文检索引擎 WindSearch: https://github.com/rock365/windsearch
请帮我点个star~谢谢你!