In this example,I will show you how to how to get all files in a folder using PHP Language. You can esay and simply get list of files in Folder in PHP.
We use the built-in function scandir()
to take files name from a directory.
The scandir() function lists the files and directories names which are present inside a specified path.
scandir()
:The scandir() function in PHP is an inbuilt function which is used to return an array of files and directories of the specified directory.
Example 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php $dir = "images/"; $list1 = scandir($dir); $list2 = scandir($dir,1); echo "<pre>"; print_r($list1); print_r($list2); |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | Array ( [0] => . [1] => .. [2] => pic1.png [3] => pic2.png [4] => pic3.png [5] => pic4.png ) Array ( [0] => pic4.png [1] => pic3.png [2] => pic2.png [3] => pic1.png [4] => .. [5] => . ) |
Example 2:
1 2 3 4 5 6 7 8 9 10 11 | <?php $dir = "images/"; $list = array_diff(scandir($dir), array('.', '..')); echo "<pre>"; print_r($list); |
Output:
1 2 3 4 5 6 7 8 9 | Array ( [2] => pic1.png [3] => pic2.png [4] => pic3.png [5] => pic4.png ) |
Example 3: Php list all files in directory recursively
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?php function getDirContents($dir, &$results = array()) { $files = scandir($dir); foreach ($files as $key => $value) { $path = realpath($dir . DIRECTORY_SEPARATOR . $value); if (!is_dir($path)) { $results[] = $path; } else if ($value != "." && $value != "..") { getDirContents($path, $results); $results[] = $path; } } return $results; } echo "<pre>"; var_dump(getDirContents('./')); |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | array(11) { [0]=> string(33) "D:\xampp\htdocs\example\data.json" [1]=> string(35) "D:\xampp\htdocs\example\example.php" [2]=> string(39) "D:\xampp\htdocs\example\images\pic1.png" [3]=> string(39) "D:\xampp\htdocs\example\images\pic2.png" [4]=> string(39) "D:\xampp\htdocs\example\images\pic3.png" [5]=> string(39) "D:\xampp\htdocs\example\images\pic4.png" [6]=> string(30) "D:\xampp\htdocs\example\images" [7]=> string(35) "D:\xampp\htdocs\example\license.txt" [8]=> string(33) "D:\xampp\htdocs\example\ork.csv" [9]=> string(32) "D:\xampp\htdocs\example\read.txt" [10]=> string(35) "D:\xampp\htdocs\example\readme.html" } |
Example 4: Get File names form Current Directory
1 2 3 4 5 6 7 8 9 10 11 | <?php $dir = "./"; $list = array_diff(scandir($dir), array('.', '..')); echo "<pre>"; print_r($list); |
Output:
1 2 3 4 5 6 7 8 9 10 11 | Array ( [2] => data.json [3] => example.php [4] => images [5] => license.txt [6] => ornek.csv [7] => readme.html ) |
Example 5: Get file name from directory
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php echo "<pre>"; $fileList = glob('./*'); foreach($fileList as $filename){ if(is_file($filename)){ echo $filename, '<br>'; } } |
Output:
1 2 3 4 5 6 7 | ./data.json ./example.php ./license.txt ./ornek.csv ./readme.html |