Simple directory iterator that is recursive and shows all files and directories/sub-directories.
I don't see any built in function to exclude certain file types, for instance in the following example I do not want to output any image related files such as .jpg
, .png
, etc. I know there are several methods of doing this , looking for advice on which would be best.
$scan_it = new RecursiveDirectoryIterator("/example_dir");
foreach(new RecursiveIteratorIterator($scan_it) as $file) {
echo $file;
}
Update:
Ok, so I'm an idiot. PHP has a builtin for this: pathinfo()
Try this:
$filetypes = array("jpg", "png");
$filetype = pathinfo($file, PATHINFO_EXTENSION);
if (!in_array(strtolower($filetype), $filetypes)) {
echo $file;
}
Original Answer:
Why not just run substr()
on the filename and see if it matches the extension of the file type you want to exclude:
$scan_it = new RecursiveDirectoryIterator("/example_dir");
foreach(new RecursiveIteratorIterator($scan_it) as $file) {
if (strtolower(substr($file, -4)) != ".jpg" &&
strtolower(substr($file, -4)) != ".jpg") {
echo $file;
}
}
You could make it easier by using regular expressions:
if (!preg_match("/\.(jpg|png)*$/i", $file, $matches)) {
echo $file;
}
You could even use an array to keep track of your file types:
$filetypes = array("jpg", "png");
if (!preg_match("/\.(" . implode("|", $filetypes) . ")*$/i", $file, $matches)) {
echo $file;
}
From PHP 5.4 can use \RecursiveCallbackFilterIterator
$iterator = new \RecursiveDirectoryIterator(getcwd(), \RecursiveDirectoryIterator::SKIP_DOTS);
$iterator = new \RecursiveCallbackFilterIterator(
$iterator,
function ($item) {
return $item->getExtension() === 'php' ? true : false;
}
);
Iterator now will contains only PHP files.
foreach($iterator as $file) {
echo $file;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With