How to Get File Name List from Folder In php?

In this article, I will share with you how to get a file name list from the folder using PHP with some simple examples.

Sometimes you need to get all the file lists from some specific folder and do some actions on that file in your PHP application. so, here I will same some sample code for how to get a file name list from a folder using PHP.

The scandir() function in PHP is an inbuilt function that is used to return an array of files and directories of the specified directory. The scandir() function lists the files and directories which are present inside a specified path.

Example - 1:

<?php 
  $mydir = 'folderName';   
  $myfiles = array_diff(scandir($mydir), array('.', '..'));   
  print_r($myfiles); 
?> 

Output :

Array ( 
 [2] => demo
 [3] => demo2
 [4] => test1.php
 [5] => test2.php
 [6] => test3.txt
)

Example - 2:

<?php
$fileList = glob('test/*');
foreach($fileList as $filename){
    if(is_file($filename)){
        echo $filename, '<br>'; 
    }   
}
?>

Output :

dummy/test1.php
dummy/test2.php
dummy/test3.txt

Example - 3:

in this example, we will get only some specific types of extension files like .php, .pdf, .jpg, etc...

<?php
$fileList = glob('test/*.php');
foreach($fileList as $filename){
    if(is_file($filename)){
        echo $filename, '<br>'; 
    }   
}
?>

Output :

dummy/test1.php
dummy/test2.php

i hope this small code help you in your development.

Tags:

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

1 Comment

SA
Hari Prasad
April 02, 2021

Great articles, keep it on!

SA
Harsukh Makwana
Fri April, 2021

Thank you!