PHP filter_list() 函数

定义和用法

filter_list() 函数用于获取所有支持的过滤器列表。

该函数返回一个关联数组,其中键是过滤器ID,值是过滤器名称。这个函数通常与 filter_id() 函数结合使用,来动态获取和验证可用的过滤器。

提示:这个函数在需要动态生成过滤器选项或检查特定过滤器是否可用时非常有用。

语法

filter_list(): array

参数

此函数没有参数。

返回值

返回一个包含所有支持的过滤器名称的关联数组,数组的键是过滤器ID,值是过滤器名称。

返回的数组格式如下:

Array
(
    [257] => int
    [258] => boolean
    [259] => float
    [272] => validate_regexp
    [277] => validate_domain
    [273] => url
    [274] => email
    [275] => ip
    [276] => mac
    // ... 更多过滤器
)

过滤器分类

分类 描述 示例过滤器
验证过滤器 用于验证数据是否符合特定格式,如果验证失败返回 false int, boolean, float, email, url, ip, mac
清理过滤器 用于清理数据,去除或编码不需要的字符 string, encoded, special_chars, full_special_chars, email, url
其他过滤器 其他特殊用途的过滤器 callback, unsafe_raw

示例

示例 1:基本用法 - 获取所有过滤器列表

<?php
// 获取所有支持的过滤器
$filters = filter_list();

echo "<h4>支持的过滤器列表:</h4>";
echo "<table border='1' cellpadding='5'>";
echo "<tr><th>过滤器ID</th><th>过滤器名称</th><th>常量名称</th></tr>";

foreach ($filters as $id => $name) {
    // 根据过滤器名称生成常量名
    $constant_name = "FILTER_" . strtoupper($name);

    // 检查是否是验证过滤器
    if (strpos($name, 'validate_') === 0) {
        $constant_name = "FILTER_" . strtoupper($name);
    } elseif ($name === 'int' || $name === 'boolean' || $name === 'float' ||
               $name === 'email' || $name === 'url' || $name === 'ip') {
        $constant_name = "FILTER_VALIDATE_" . strtoupper($name);
    } elseif ($name === 'string' || $name === 'encoded' || $name === 'special_chars') {
        $constant_name = "FILTER_SANITIZE_" . strtoupper($name);
    }

    echo "<tr><td>$id</td><td>$name</td><td>$constant_name</td></tr>";
}

echo "</table>";
echo "<p>总共找到 " . count($filters) . " 个过滤器</p>";
?>

示例 2:动态生成过滤器选择菜单

<?php
// 动态生成过滤器选择表单
function generateFilterSelect($selected = '') {
    $filters = filter_list();

    echo "<select name='filter_type' class='form-select'>";
    echo "<option value=''>-- 选择过滤器 --</option>";

    foreach ($filters as $id => $name) {
        $selectedAttr = ($selected == $name) ? ' selected' : '';

        // 获取人类可读的描述
        $descriptions = [
            'int' => '验证整数',
            'boolean' => '验证布尔值',
            'float' => '验证浮点数',
            'email' => '验证邮箱地址',
            'url' => '验证URL地址',
            'ip' => '验证IP地址',
            'string' => '清理字符串(去除标签)',
            'encoded' => 'URL编码字符串',
            'special_chars' => 'HTML实体编码特殊字符'
        ];

        $description = isset($descriptions[$name]) ? " - {$descriptions[$name]}" : "";

        echo "<option value='$name'$selectedAttr>$name (ID: $id)$description</option>";
    }

    echo "</select>";
}

// 使用示例
echo "<form method='post'>";
echo "<div class='mb-3'>";
echo "<label for='filter_select' class='form-label'>选择过滤器类型:</label>";
generateFilterSelect(isset($_POST['filter_type']) ? $_POST['filter_type'] : '');
echo "</div>";
echo "<div class='mb-3'>";
echo "<label for='input_value' class='form-label'>输入要验证的值:</label>";
echo "<input type='text' name='input_value' class='form-control' value='" .
     (isset($_POST['input_value']) ? htmlspecialchars($_POST['input_value']) : '') . "'>";
echo "</div>";
echo "<button type='submit' class='btn btn-primary'>验证</button>";
echo "</form>";

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['filter_type'], $_POST['input_value'])) {

    $filterName = $_POST['filter_type'];
    $inputValue = $_POST['input_value'];

    if (!empty($filterName)) {
        // 获取过滤器ID
        $filterId = filter_id($filterName);

        if ($filterId !== false) {
            // 应用过滤器
            $filteredValue = filter_var($inputValue, $filterId);

            echo "<div class='mt-3 alert alert-info'>";
            echo "<h5>验证结果:</h5>";
            echo "过滤器名称: $filterName<br>";
            echo "过滤器ID: $filterId<br>";
            echo "原始值: " . htmlspecialchars($inputValue) . "<br>";
            echo "过滤结果: ";

            if ($filteredValue === false) {
                echo "<span class='text-danger'>验证失败</span>";
            } elseif ($filteredValue === null) {
                echo "<span class='text-warning'>返回 null</span>";
            } else {
                echo "<span class='text-success'>验证成功: " .
                     htmlspecialchars($filteredValue) . "</span>";
            }

            echo "</div>";
        } else {
            echo "<div class='alert alert-danger'>无效的过滤器名称</div>";
        }
    }
}
?>

示例 3:检查特定过滤器是否可用

<?php
// 检查特定过滤器是否在支持列表中
function isFilterSupported($filterName) {
    $filters = filter_list();

    // 检查过滤器名称是否在值中
    return in_array($filterName, $filters);
}

// 测试各种过滤器
$testFilters = [
    'int', 'boolean', 'float', 'email', 'url', 'ip',
    'string', 'encoded', 'special_chars', 'nonexistent_filter'
];

echo "<h4>过滤器支持情况检查:</h4>";
echo "<table class='table table-bordered'>";
echo "<tr><th>过滤器名称</th><th>是否支持</th><th>过滤器ID</th></tr>";

foreach ($testFilters as $filter) {
    $isSupported = isFilterSupported($filter);
    $filterId = filter_id($filter);

    $statusClass = $isSupported ? 'text-success' : 'text-danger';
    $statusText = $isSupported ? '支持' : '不支持';

    echo "<tr>";
    echo "<td>$filter</td>";
    echo "<td class='$statusClass'>$statusText</td>";
    echo "<td>" . ($filterId !== false ? $filterId : 'N/A') . "</td>";
    echo "</tr>";
}

echo "</table>";
?>

示例 4:将过滤器分类显示

<?php
// 将过滤器按类型分类
function categorizeFilters() {
    $filters = filter_list();

    $categories = [
        'validation' => [
            'name' => '验证过滤器',
            'filters' => []
        ],
        'sanitization' => [
            'name' => '清理过滤器',
            'filters' => []
        ],
        'other' => [
            'name' => '其他过滤器',
            'filters' => []
        ]
    ];

    // 定义每种类型的过滤器名称模式
    $validationPatterns = ['int', 'boolean', 'float', 'email', 'url', 'ip', 'mac', 'validate_'];
    $sanitizationPatterns = ['string', 'encoded', 'special_chars', 'full_special_chars', 'sanitize_'];

    foreach ($filters as $id => $name) {
        $categorized = false;

        // 检查是否是验证过滤器
        foreach ($validationPatterns as $pattern) {
            if (strpos($name, $pattern) === 0 || $name === $pattern) {
                $categories['validation']['filters'][$id] = $name;
                $categorized = true;
                break;
            }
        }

        if (!$categorized) {
            // 检查是否是清理过滤器
            foreach ($sanitizationPatterns as $pattern) {
                if (strpos($name, $pattern) === 0 || $name === $pattern) {
                    $categories['sanitization']['filters'][$id] = $name;
                    $categorized = true;
                    break;
                }
            }
        }

        // 如果仍未分类,则放到其他
        if (!$categorized) {
            $categories['other']['filters'][$id] = $name;
        }
    }

    return $categories;
}

// 显示分类后的过滤器
$categorized = categorizeFilters();

echo "<h4>过滤器分类:</h4>";

foreach ($categorized as $category) {
    if (!empty($category['filters'])) {
        echo "<div class='mb-4'>";
        echo "<h5>{$category['name']} (" . count($category['filters']) . "个)</h5>";
        echo "<table class='table table-sm table-bordered'>";
        echo "<tr><th style='width: 100px;'>ID</th><th>名称</th></tr>";

        foreach ($category['filters'] as $id => $name) {
            echo "<tr><td>$id</td><td>$name</td></tr>";
        }

        echo "</table>";
        echo "</div>";
    }
}
?>

示例 5:构建动态过滤器配置系统

<?php
// 动态过滤器配置类
class DynamicFilterSystem {
    private $availableFilters;

    public function __construct() {
        $this->availableFilters = filter_list();
    }

    // 获取所有可用过滤器
    public function getAllFilters() {
        return $this->availableFilters;
    }

    // 根据类型获取过滤器
    public function getFiltersByType($type) {
        $filtered = [];

        foreach ($this->availableFilters as $id => $name) {
            if ($type === 'validation' && $this->isValidationFilter($name)) {
                $filtered[$id] = $name;
            } elseif ($type === 'sanitization' && $this->isSanitizationFilter($name)) {
                $filtered[$id] = $name;
            }
        }

        return $filtered;
    }

    // 检查是否是验证过滤器
    private function isValidationFilter($name) {
        $validationFilters = ['int', 'boolean', 'float', 'email', 'url', 'ip', 'mac'];
        return in_array($name, $validationFilters) || strpos($name, 'validate_') === 0;
    }

    // 检查是否是清理过滤器
    private function isSanitizationFilter($name) {
        $sanitizationFilters = ['string', 'encoded', 'special_chars', 'full_special_chars'];
        return in_array($name, $sanitizationFilters) || strpos($name, 'sanitize_') === 0;
    }

    // 创建动态过滤器配置
    public function createFilterConfig($fieldConfigs) {
        $config = [];

        foreach ($fieldConfigs as $field => $filterName) {
            if (in_array($filterName, $this->availableFilters)) {
                $filterId = filter_id($filterName);

                if ($filterId !== false) {
                    $config[$field] = $filterId;
                }
            }
        }

        return $config;
    }

    // 显示过滤器统计信息
    public function displayStats() {
        $total = count($this->availableFilters);
        $validation = count($this->getFiltersByType('validation'));
        $sanitization = count($this->getFiltersByType('sanitization'));
        $other = $total - $validation - $sanitization;

        echo "<div class='alert alert-secondary'>";
        echo "<h5>过滤器统计:</h5>";
        echo "总过滤器数: $total<br>";
        echo "验证过滤器: $validation<br>";
        echo "清理过滤器: $sanitization<br>";
        echo "其他过滤器: $other";
        echo "</div>";
    }
}

// 使用示例
$filterSystem = new DynamicFilterSystem();

echo "<h4>动态过滤器系统</h4>";

// 显示统计信息
$filterSystem->displayStats();

// 显示所有过滤器
echo "<h5>所有可用过滤器:</h5>";
$allFilters = $filterSystem->getAllFilters();
echo "<pre>" . print_r($allFilters, true) . "</pre>";

// 创建动态配置
echo "<h5>创建动态过滤器配置:</h5>";
$fieldConfigs = [
    'username' => 'string',
    'email' => 'email',
    'age' => 'int',
    'website' => 'url'
];

$config = $filterSystem->createFilterConfig($fieldConfigs);
echo "<pre>" . print_r($config, true) . "</pre>";

// 使用配置过滤数据
if (!empty($config)) {
    $testData = [
        'username' => 'John<script>alert("xss")</script>Doe',
        'email' => 'john@example.com',
        'age' => '25',
        'website' => 'https://www.example.com'
    ];

    echo "<h5>测试过滤效果:</h5>";
    foreach ($config as $field => $filterId) {
        if (isset($testData[$field])) {
            $result = filter_var($testData[$field], $filterId);
            echo "$field: 原始值 = '" . htmlspecialchars($testData[$field]) . "', ";
            echo "过滤后 = '" . htmlspecialchars($result) . "'<br>";
        }
    }
}
?>

注意事项

  • 返回值类型filter_list() 始终返回一个数组,即使没有过滤器可用
  • PHP版本差异:不同PHP版本支持的过滤器可能不同,较新的版本通常有更多过滤器
  • 过滤器ID:过滤器ID在不同PHP版本中可能不一致,建议使用过滤器名称而非ID
  • 性能考虑:虽然获取过滤器列表很快,但不应在循环中频繁调用此函数
  • 与filter_id()配合使用:通常与 filter_id() 函数一起使用,将过滤器名称转换为ID
  • 默认过滤器FILTER_DEFAULT 不会出现在 filter_list() 的返回列表中
  • 扩展要求:过滤器功能需要PHP的filter扩展,大多数PHP环境默认启用

常用过滤器参考

过滤器名称 对应常量 描述 PHP版本
int FILTER_VALIDATE_INT 验证整数 ≥ 5.2.0
boolean FILTER_VALIDATE_BOOLEAN 验证布尔值 ≥ 5.2.0
float FILTER_VALIDATE_FLOAT 验证浮点数 ≥ 5.2.0
email FILTER_VALIDATE_EMAIL 验证邮箱地址 ≥ 5.2.0
url FILTER_VALIDATE_URL 验证URL地址 ≥ 5.2.0
ip FILTER_VALIDATE_IP 验证IP地址 ≥ 5.2.0
string FILTER_SANITIZE_STRING 清理字符串(去除HTML标签) ≥ 5.2.0
encoded FILTER_SANITIZE_ENCODED URL编码字符串 ≥ 5.2.0
special_chars FILTER_SANITIZE_SPECIAL_CHARS HTML实体编码特殊字符 ≥ 5.2.0
validate_regexp FILTER_VALIDATE_REGEXP 使用正则表达式验证 ≥ 5.2.0
validate_domain FILTER_VALIDATE_DOMAIN 验证域名 ≥ 7.0.0

相关函数

浏览器支持

该函数是 PHP 后端函数,与浏览器无关。需要 PHP 5.2.0 或更高版本。