Reputation: 51
I have this function which supposed to lead to the correct image folder (images) and shows its images, but it shows the all the images in the root path & the ones in (images) folder. what I have to change to make it shows the images that belongs to (images) folder only?.
function searchSite( $path = 'images', $level = 0 ) {
$skip = array( 'cgi-bin', '.', '..' );
$look_for = array( '.jpg', '.gif', '.png', '.jpeg' );
$dh = @opendir( $path );
while ( false !== ( $file = readdir( $dh ) ) ) {
$file_ext = substr( $file, -4, 4 );
if ( !in_array( $file, $skip ) ) {
if ( is_dir( "$path/$file" ) ) {
searchSite( "$path/$file", ( $level + 1 ) );
} else if ( in_array( $file_ext, $look_for ) ) {
echo "<option value='$path/$file' />$file</option>";
}
}
closedir( $dh );
}
Upvotes: 0
Views: 104
Reputation: 5119
PHP got its own filesystem and filter classes. With these classes you can easily iterator recursivly over a directory tree to get all the files you want. Nowadays it is kinda deprecated to code your own functionality, because the build in iterator and filter classes are much more efficient and it is not necessary to re-invent the wheel.
Here 's a short example how to use the build in filesystem and filter classes.
<?php
declare(strict_types=1);
namespace Marcel;
use FilesystemIterator;
use RecursiveCallbackFilterIterator;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
$directory = new RecursiveDirectoryIterator('../assets/images/', FilesystemIterator::FOLLOW_SYMLINKS);
$filter = new RecursiveCallbackFilterIterator($directory, function($current, $key, $iterator) {
if ($current->isDir()) {
return !in_array($current->getFilename(), ['.', '..', 'bla']);
} else {
return in_array($current->getExtension(), ['jpg', 'png']);
}
});
$iterator = new RecursiveIteratorIterator($filter);
$files = [];
foreach ($iterator as $file) {
$files[] = $file->getPathname();
}
var_dump($files);
Upvotes: 2