How to Get List of File In Folder In PHP

  354 views   5 months ago 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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]