PHP List count all files subfolders in a directory

Click to rate this tutorial!
[Total: 1 Average: 1]

PHP has functions that can be used for working with files and folders inside a directory. We are using 4 main functions in php opendir(), is_dir(),count() and readdir()

I am using opendir() to open the directory and readdir() to display the files.

Also refer to,

Working With Directories Using PHP
PHP List All folders And Subfolders Under A Directory
PHP Find Files In A Directory
Create A Folder / Directory Using PHP

Features Of This Simple Script
———————–
Listing files, No empty / blank area will be displayed on the page during listing.
Script has ability to check whether it is a file or directory.
Listed files will also have a hyperlink along with their name so that if you have a requirement to pass the filename as query string to another webpage you can easily do that here.
If there are no files under a directory then it will display an alert stating no files in the directory.
It also count number of files inside a directory.
It can also count the number of folders too.

This script is very simple and easy to understand, all you have to do is change directory name for $dir_name variable according to your requirement. Make sure you provide name of the directory in this format (/)

$dir_name = 'myuploadir/';
if ($handle = opendir($dir_name )) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(is_dir($dir_name.$file))
{
echo " ".$dir_name.$file." Is A Directory";
//If Directory Do Something Here
}
else
{
$page_name=substr($file, 0, strpos($file, "."));
echo "<br>Name Of The File <a href='nextpage.php?filename=".$file."'>".$file."</a>";
}
}
}
}
echo "<br>";
closedir($handle);
$num_files = count(glob($dir_name.'/*.*'));
echo "<p>Number Of Files $num_files";
if($num_files == 0)
{
echo "No files found in this directory.";
}

Click to rate this tutorial!
[Total: 1 Average: 1]

Leave a Reply

Your email address will not be published.