HS Banner
Back
List All Files in a Directory Using PHP

Author: Admin 04/05/2022
Language: PHP
Views: 201
Tags: list files directory php glob scandir opendir readdir closedir filesystemiterator


Description:

In PHP there are several ways to get a list of files in a PHP application.

Article:

Here's the opendir, readdir, and closedir functions

<?php
$arrFiles = array();
$handle = opendir('/your_dir');
 
if ($handle) {
    while (($entry = readdir($handle)) !== FALSE) {
        $arrFiles[] = $entry;
    }
}
 
closedir($handle);
?>

PHP: opendir - Manual

PHP: readdir - Manual

PHP: closedir - Manual

 

Here's the scandir function

<?php
$arrFiles = scandir('/your_dir');
?>

PHP: scandir - Manual

 

Here's the glob function

Here we use the * pattern to read all contents.

<?php
$arrFiles = glob('/your_dir/*');
?>

Here we use the *.pdf pattern to get PDF files in the directory.

<?php
$arrFiles = glob('/your_dir/*.pdf');
?>

PHP: glob - Manual

 

Here's the dir function

<?php
$arrFiles = array();
$objDir = dir("/your_dir");
 
while (false !== ($entry = $objDir->read())) {
   $arrFiles[] = $entry;
}
 
$objDir->close();
?>

PHP: dir - Manual

 

Here's the filesystemterator Class

<?php
$arrFiles = array();
$iterator = new FilesystemIterator("/your_dir");
 
foreach($iterator as $entry) {
    $arrFiles[] = $entry->getFilename();
}
?>

PHP: FilesystemIterator - Manual


Back
Comments
Add Comment
There are no comments yet.