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

Asked

Viewed 987 times

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 count only the files from a folder, ignoring the folders that are inside it.

2 answers

4


2

The most appropriate way in my view would be to use the class FileSystemIterator, which is part of the standard class set offered by PHP.

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

echo iterator_count($iterator);

In that case, we have to use SKIP_DOTS, not to take directory representations as . and ...

Observing: The class FilesysteIterator does not implement the interface Countable. Therefore the use of the function iterator_count.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.