Reputation: 13
Please see the following code which I have tried.
echo scanDirectoryImages("Images");
function scanDirectoryImages($directory, array $exts = array('jpeg', 'jpg',
'gif', 'png'))
{
$html = '';
if (
is_readable($directory)
&& (file_exists($directory) || is_dir($directory))
) {
$directoryList = opendir($directory);
while($file = readdir($directoryList)) {
if ($file != '.' && $file != '..') {
$path = $directory . '/' . $file;
if (is_readable($path)) {
if (is_dir($path)) {
return scanDirectoryImages($path, $exts);
}
if (
is_file($path)
&& in_array(end(explode('.', end(explode('/', $path)))),
$exts)
) {
$html .= '<img src="' . $path
. '" style="max-height:200px;max-width:200px"
value="<?php echo basename($path)"/> ';
}
}
}
}
closedir($directoryList);
}
return $html;
}
It is returning only the images from my sub directories but not the path of sub-directories what i actually want. Also,I'am working on a server and not localhost which is creating a problem to set $path. please help!!!
Upvotes: 1
Views: 46
Reputation: 12332
I'd like to show you a really easy way to get all of the files with a particular extension from a directory.
This makes use of various Iterators and filters
the FilterIterator::accept()
is the rule to which files are included in the iteration.
class ImagesOnlyFilterIterator extends FilterIterator
{
function accept()
{
return in_array( strtolower( $this->current()->getExtension() ), array( 'jpeg', 'jpg', 'gif', 'png', 'bmp', 'tif', 'tiff' ), true );
}
}
$path = '/foo/bar/whatever';
foreach( new ImagesOnlyFilterIterator( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path ) ) ) as $image )
{
echo $image . PHP_EOL;
}
$image
will actually be a SplFileInfo object, and will contain other various properties for you to use.
Upvotes: 2