readdir 是一个用于读取目录内容的函数。要过滤特定文件类型,你可以在遍历目录内容时检查每个文件的扩展名。以下是一个使用 PHP 的示例,展示了如何使用 readdir 过滤特定文件类型(例如,仅显示 .txt 文件):
<?php
$directory = 'path/to/your/directory'; // 替换为你的目录路径
$allowedExtension = '.txt'; // 设置允许的文件扩展名
if (is_dir($directory)) {
$files = scandir($directory); // 读取目录内容
foreach ($files as $file) {
if ($file !== '.' && $file !== '..') { // 排除当前目录和上级目录
$fileExtension = pathinfo($file, PATHINFO_EXTENSION); // 获取文件扩展名
if (strtolower($fileExtension) === strtolower($allowedExtension)) { // 检查文件扩展名是否匹配
echo $file . PHP_EOL; // 输出匹配的文件名
}
}
}
} else {
echo "The directory does not exist.";
}
?>
请注意,这个示例使用了 scandir 函数,因为它比 readdir 更易于使用。但是,如果你想使用 readdir,可以参考以下示例:
<?php
$directory = 'path/to/your/directory'; // 替换为你的目录路径
$allowedExtension = '.txt'; // 设置允许的文件扩展名
if (is_dir($directory)) {
$handle = opendir($directory); // 打开目录
while (($file = readdir($handle)) !== false) {
if ($file !== '.' && $file !== '..') { // 排除当前目录和上级目录
$fileExtension = pathinfo($file, PATHINFO_EXTENSION); // 获取文件扩展名
if (strtolower($fileExtension) === strtolower($allowedExtension)) { // 检查文件扩展名是否匹配
echo $file . PHP_EOL; // 输出匹配的文件名
}
}
}
closedir($handle); // 关闭目录句柄
} else {
echo "The directory does not exist.";
}
?>
这两个示例都会输出指定目录中所有 .txt 文件的文件名。你可以根据需要修改 $allowedExtension 变量来过滤其他文件类型。