How can opendir, while, readdir, and is_file functions be used to count files in a folder in PHP?

To count the number of files in a folder in PHP, you can use the opendir function to open the directory, while loop to iterate through the files, readdir function to read each file, and is_file function to check if the item is a file. By incrementing a counter for each file found, you can keep track of the total number of files in the folder.

$dir = "path/to/folder";
$counter = 0;

if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
        if (is_file($dir . "/" . $file)) {
            $counter++;
        }
    }
    closedir($handle);
}

echo "Total number of files in the folder: " . $counter;