How to find folders/Files in a directory Using scandir() in PHP

This PHP tutorial helps to read folders/files from a directory. I will provide a simple PHP script that read all files and lists them down into HTML table.

The functions is_dir() and is_file() can be used to determine whether a folder or a file.

I am using Bootstrap 3 CSS framework for HTML table listing, PHP provides scandir() method to read files from a directory location.

You can use this method for Linux as well as with windows, You just need to pass the correct source directory path.

Let’s read all folder of /htdocs folders using scandir() method.

$dir    = '/phpflow';
$files = array_slice(scandir($dir), 2);

scandir() method all list with two extra entry '.' and '..', I am escaping that entry using array_slice() method.

$files variable will have all folders and files of /htdocs directory in the array. They don’t read inner folder files since it does not follow the recursive method to read files.

Now we will iterate on $files variables and bind data with the table.

<div class="container">
<table class="table table-hover">
<thead>
<tr>
<th>#id</th>
<th>Source URL</th>
</tr>
</thead>
<tbody><?php $i =0 ;foreach($files as $file) {?>
<tr>
<td><?php echo $i;?></td>
<td><a href="<?php echo $file;?>"><!--?php echo $file;$i++;?></a></td>
</tr>
<?php }?></tbody>
</table>
</div>

Output:

folder_list

PHP using scandir() to find folders in a directory

You can also print all folders and files of a directory if you don’t want to list in a table.

$scan = scandir('htdocs');
foreach($scan as $file) {
   if (!is_dir("htdocs/$file")) {
      echo $file.'\n';
   }
}

Leave a Reply

Your email address will not be published. Required fields are marked *