How to List Files in a Directory Using PHP
To list files in a directory in PHP, use the
scandir() function which returns an array of filenames. Alternatively, use the DirectoryIterator class for more control and filtering options.Syntax
The simplest way to list files is with scandir(). It takes the directory path as input and returns an array of filenames including . and ...
Example syntax:
scandir(string $directory, int $sorting_order = SCANDIR_SORT_ASCENDING): array
For more control, use DirectoryIterator which lets you loop through directory contents and check file types.
php
<?php $files = scandir('/path/to/directory'); foreach ($files as $file) { echo $file . "\n"; } // Using DirectoryIterator $dir = new DirectoryIterator('/path/to/directory'); foreach ($dir as $fileinfo) { if (!$fileinfo->isDot()) { echo $fileinfo->getFilename() . "\n"; } } ?>
Example
This example lists all files in the current directory, skipping the special . and .. entries using scandir(). It prints each filename on a new line.
php
<?php $directory = __DIR__; // current directory $files = scandir($directory); foreach ($files as $file) { if ($file !== '.' && $file !== '..') { echo $file . "\n"; } } ?>
Output
index.php
readme.txt
config.php
Common Pitfalls
Common mistakes when listing files include:
- Not filtering out
.and..which represent the current and parent directories. - Assuming all entries are files; directories can appear too.
- Using relative paths without knowing the current working directory.
Always check if an entry is a file or directory if you want only files.
php
<?php // Wrong: prints . and .. entries $files = scandir('/path/to/dir'); foreach ($files as $file) { echo $file . "\n"; } // Right: filter out . and .. and check if file $files = scandir('/path/to/dir'); foreach ($files as $file) { if ($file !== '.' && $file !== '..' && is_file('/path/to/dir/' . $file)) { echo $file . "\n"; } } ?>
Quick Reference
- scandir(path): Returns array of all entries including
.and... - DirectoryIterator: Object-oriented way to iterate directory contents.
- is_file(path): Checks if a path is a file.
- Always filter out
.and..when listing files.
Key Takeaways
Use
scandir() to get an array of directory contents quickly.Filter out
. and .. to avoid special directory entries.Use
is_file() or DirectoryIterator to distinguish files from directories.Always provide the correct path to avoid unexpected results.
For more control, prefer
DirectoryIterator over scandir().