简体   繁体   中英

How can I print the list of directory and sub-directory along with files inside sub-directory

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!!!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM