# 输入过滤/反XSS

# filter

我们提供了专用于输入过滤的filter全局公共函数。
系统默认提供的三个基类Api、Backend、Frontend都已经配置好了过滤规则,像这样:

// app/common/controller/Api.php(API基类文件)

protected function initialize(): void
{
    // 使用全局公共函数 filter() 过滤输入
    $this->request->filter('filter');
}

// ...
  • 推荐您新建控制器时,都先继承于Api、Backend、Frontend之一。
  • 如果需要改变过滤规则,只需在父类中再次使用$this->request->filter('strip_tags');重新设置过滤规则即可,它会覆盖基类的设置。
  • filter函数的定义如下:
function filter(string $string): string
{
    // 去除字符串两端空格(对防代码注入有一定作用)
    $string = trim($string);

    // 过滤html和php标签
    $string = strip_tags($string);

    // 特殊字符转实体
    return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, 'UTF-8');
}
  • filter的返回值为string,若需接受输入为其他类型,可以使用修饰符,比如$this->request->get('id/d');,详见TP文档 (opens new window)
  • 我们使用了strip_tags过滤标签,这是为了更好(看)的输出,它的存在可能会造成<、<=、未闭合标签也被意外的过滤掉,您也可以考虑使用下方的clean_xss来过滤

# clean_xss

我们内置了一个反XSS公共函数,以便您随时使用。

# 使用示例

<?php

$harm_string = "Hello, i try to <script>alert('Hack');</script> your site";
$harmless_string = clean_xss($harm_string);
// string(26) "Hello, i try to your site"


$harm_string = "<IMG SRC=&#x6A&#x61&#x76&#x61&#x73&#x63&#x72&#x69&#x70&#x74&#x3A&#x61&#x6C&#x65&#x72&#x74&#x28&#x27&#x58&#x53&#x53&#x27&#x29>";
$harmless_string = clean_xss($harm_string);
// <IMG >


$harm_string = "<a href='&#x2000;javascript:alert(1)'>CLICK</a>";
$harmless_string = clean_xss($harm_string);
// <a >CLICK</a>

# 请求输入反XSS

设置之后,再接受的请求输入,就会使用它进行过滤了


$this->request->filter('clean_xss');

// 过滤了 XSS 的 $data
$data = $this->request->post();

通常用于富文本数据的过滤,它比filter()慢,使用可视化CRUD生成的富文本,默认已经使用本函数过滤,无需额外设置。

# voku/anti-xss 依赖

框架内置了voku/anti-xss (opens new window)clean_xss()正是依赖它实现的,您也可以去它的主页查阅更多使用技巧。