Current Location: Home> Latest Articles> How to get a loaded list of filters using PHP's stream_get_filters function?

How to get a loaded list of filters using PHP's stream_get_filters function?

gitbox 2025-05-20

In PHP, stream filters are a powerful mechanism that allows you to process data before it is read or written to a stream. For example, you can automatically convert the content to uppercase when reading a file, or automatically compress the content when writing to a network request.

To view all filters that have been loaded in the current PHP environment, you can use the stream_get_filters() function. This function returns an array containing all registered filter names.

Let’s take a look at specific usage examples below.

Basic usage

 <?php
$filters = stream_get_filters();

echo "List of loaded filters:\n";
foreach ($filters as $filter) {
    echo "- {$filter}\n";
}
?>

After running this code, you will see an output similar to the following (depending on your PHP environment):

 List of loaded filters:
- string.rot13
- string.toupper
- string.tolower
- convert.iconv.*
- convert.*
- zlib.*
- bzip2.*

These filters can be directly used in functions such as stream_filter_append() , stream_filter_prepend() , etc., to dynamically process the flow.

Example: Use filters to modify file contents

Suppose we have a text file example.txt , and the contents are all lowercase letters. We want to read it and automatically convert to uppercase when output.

 <?php
$filename = 'example.txt';
$handle = fopen($filename, 'r');

if ($handle) {
    stream_filter_append($handle, 'string.toupper');

    while (!feof($handle)) {
        echo fgets($handle);
    }

    fclose($handle);
} else {
    echo "Unable to open the file: {$filename}";
}
?>

This code will automatically convert the content to uppercase when reading the file without manually calling strtoupper() .

Check if a filter is supported

If your code depends on a specific filter, it is best to check if it is loaded first:

 <?php
$neededFilter = 'string.toupper';
$filters = stream_get_filters();

if (in_array($neededFilter, $filters)) {
    echo "Filter {$neededFilter} Loaded,Ready to use。\n";
} else {
    echo "Filter {$neededFilter} Not available,Check, pleasePHPConfiguration。\n";
}
?>

Use filters in URL

In some cases, you might use a stream filter through a URL, for example to access php://filter :

 <?php
$url = 'php://filter/read=string.toupper/resource=https://gitbox.net/example.txt';
$content = file_get_contents($url);

if ($content !== false) {
    echo $content;
} else {
    echo "Unable to read remote resources。";
}
?>

This code converts it directly to capitalization when reading content from https://gitbox.net/example.txt .