Author: Admin 04/05/2022
Language:
PHP
Tags: list files directory php glob scandir opendir readdir closedir filesystemiterator
In PHP there are several ways to get a list of files in a PHP application.
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);
?>
Here's the scandir function
<?php
$arrFiles = scandir('/your_dir');
?>
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');
?>
Here's the dir function
<?php
$arrFiles = array();
$objDir = dir("/your_dir");
while (false !== ($entry = $objDir->read())) {
$arrFiles[] = $entry;
}
$objDir->close();
?>
Here's the filesystemterator Class
<?php
$arrFiles = array();
$iterator = new FilesystemIterator("/your_dir");
foreach($iterator as $entry) {
$arrFiles[] = $entry->getFilename();
}
?>
PHP: FilesystemIterator - Manual