Return total number of files within a folder using PHP

前端 未结 10 880
花落未央
花落未央 2020-12-28 20:31

Is there a better/simpler way to find the number of images in a directory and output them to a variable?

function dirCount($dir) {
  $x = 0;
  while (($file          


        
相关标签:
10条回答
  • 2020-12-28 20:48

    The aforementioned code

    $count = count(glob("*.{jpg,png,gif,bmp}"));
    

    is your best best, but the {jpg,png,gif} bit will only work if you append the GLOB_BRACE flag on the end:

    $count = count(glob("*.{jpg,png,gif,bmp}", GLOB_BRACE));
    
    0 讨论(0)
  • 2020-12-28 20:59

    you could use glob...

    $count = 0;
    foreach (glob("*.*") as $file) {
        if (isImage($file)) ++$count;
    }
    

    or, I'm not sure how well this would suit your needs, but you could do this:

    $count = count(glob("*.{jpg,png,gif,bmp}"));
    
    0 讨论(0)
  • 2020-12-28 21:03

    I use this to return a count of ALL files in a directory except . and ..

    return count(glob("/path/to/file/[!\.]*"));
    

    Here is a good list of glob filters for file matching purposes.

    0 讨论(0)
  • 2020-12-28 21:04

    You could also make use of the SPL to filter the contents of a DirectoryIterator using your isImage function by extending the abstract FilterIterator class.

    class ImageIterator extends FilterIterator {
    
        public function __construct($path)
        {
            parent::__construct(new DirectoryIterator($path));
        }
    
        public function accept()
        {
            return isImage($this->getInnerIterator());
        }
    }
    

    You could then use iterator_count (or implement the Countable interface and use the native count function) to determine the number of images. For example:

    $images = new ImageIterator('/path/to/images');
    printf('Found %d images!', iterator_count($images));
    

    Using this approach, depending on how you need to use this code, it might make more sense to move the isImage function into the ImageIterator class to have everything neatly wrapped up in one place.

    0 讨论(0)
  • 2020-12-28 21:05

    This will give you the count of what is in your dir. I'll leave the part about counting only images to you as I am about to fallll aaasssllleeelppppppzzzzzzzzzzzzz.

    iterator_count(new DirectoryIterator('path/to/dir/'));
    
    0 讨论(0)
  • 2020-12-28 21:05
    $nfiles = glob("/path/to/file/[!\\.]*");
    
    if ($nfiles !== FALSE){
    
        return count($nfiles);
    
    } else {
    
        return 0;
    
    }
    
    0 讨论(0)
提交回复
热议问题