Php

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.

Related Post
$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:

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';
   }
}

Recent Posts

Configure and Retrieve S3 Information Using Laravel PHP-AWS-SDK

This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More

2 months ago

What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More

8 months ago

Laravel Table Relationship Methods With Example

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More

8 months ago

Exploring the Power of Laravel Eloquent Join?

We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More

9 months ago

Quick and Easy Installation of Laravel Valet

in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More

9 months ago

What is Laravel Soft Delete and How Does it Work?

I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More

9 months ago

Categories