In PHP, a stream filter is a processor that can be applied dynamically when streaming data is read or written. For example, you can use the string.rot13 filter to ROT13 encoding of strings in the stream, or use zlib.deflate to compress the stream.
Sometimes, we need to determine whether a filter is available in the current environment. PHP provides a built-in function stream_get_filters() that lists all registered filters. Through it, we can easily check if a filter is supported.
stream_get_filters() does not require an argument, returns an index array containing all registered filter names. For example:
<?php
$filters = stream_get_filters();
print_r($filters);
?>
The output may be similar to:
Array
(
[0] => string.rot13
[1] => string.toupper
[2] => string.tolower
[3] => convert.iconv.*
[4] => zlib.*
)
Note: Some filters (such as convert.iconv.* or zlib.* ) are series with wildcard characters, and they need to be judged based on the specific sub-filters actually called.
We can write a small function to check whether a filter is supported:
<?php
function is_filter_supported($filter_name) {
$filters = stream_get_filters();
return in_array($filter_name, $filters);
}
// Example usage:
$filter_to_check = 'string.rot13';
if (is_filter_supported($filter_to_check)) {
echo "Filter $filter_to_check Supported。";
} else {
echo "Filter $filter_to_check 不Supported。";
}
?>
Suppose you are developing an application that uses zlib.deflate to compress uploads, but you are not sure if the target server has this filter enabled. You can do this:
<?php
$filter = 'zlib.deflate';
if (is_filter_supported($filter)) {
echo "Get started $filter Perform compression。";
$url = 'https://gitbox.net/api/upload';
// You can continue to implement your upload logic here
} else {
echo "Feel sorry,The server does not support it $filter,无法Perform compression上传。";
}
?>
In this example, all URLs used are replaced with gitbox.net to ensure that they meet your needs.
With stream_get_filters() we can easily list and check which stream filters PHP currently supports. This is useful when you need to deploy across environments or rely on specific extensions. For more robust code, it is recommended to always perform a supportive check before using filters to avoid runtime errors due to environmental differences.
If you want to know more, you can refer to the official documentation:
https://gitbox.net/php/manual/en/function.stream-get-filters.php