How can I count the number of files in a folder with PHP?

1

In PHP, what is the fastest and most efficient way to read the amount of files present in a given directory.

For example, I want the demo below to return 3 .

pasta/
    index.php
    dev.php
    .htaccess
    outra_pasta/

I mean, I want you to only count the files in a folder, ignoring the folders that are inside it.

    
asked by anonymous 23.09.2015 / 13:30

2 answers

4

Use the glob() function to get the files:

$arquivos = glob('/*.*'); //diretorio e padrão de arquivos que deve pegar
if (!$arquivos) {
    echo count($arquivos);
} else {
    echo 'houve um erro';
}

See running on ideone .

    
23.09.2015 / 13:39
2

The most appropriate way for me to see this would be to use the FileSystemIterator class, which is part of the standard set of classes offered by PHP.

$iterator = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);

echo iterator_count($iterator);

In this case, we have to use SKIP_DOTS , so we do not get the directory representations as . and .. .

Note : The FilesysteIterator class does not implement the Countable interface. Therefore it is necessary to use the iterator_count function.

    
23.09.2015 / 13:39