WP-Mix

A fresh mix of code snippets and tutorials

PHP List All Directory Files

Here are three ways to list all files in a directory via PHP: via iterator class, file function, and while loop (in order of preference).

Method 1: Iterator Class

Here is my favorite way to list directory contents:

class MyFileIterator extends FilterIterator {
	
	public function __construct($dir) {
		parent::__construct(new DirectoryIterator($dir));
	}

	public function accept() {
		$f = parent::current();
		return !($f->isDot() or $f->getFileName() == "Thumbs.db");
	}
	
}

This class ignores any files named Thumbs.db (just an example, you can remove or add more ignored files, etc.).

Usage:

Here is the basic usage of the iterator class:

foreach (new MyFileIterator($dir) as $f) echo (string)$f . "\n";

Or you can create a function:

function listFiles($dir) {
	
	foreach (new DirectoryIterator($dir) as $f) {
		
		if ($f->isDot()) continue;
		
		printf('%s', $f->getPathname(), $f->getFilename());
		
	}
	
}

Source: php.net

Method 2: File Function

This simple function gets all files in the specified directory and returns them as an array.

function dirList($directory) {
	
	$results = array();
	
	$handler = opendir($directory);
	
	while ($file = readdir($handler)) {
		
		// if $file isn't this directory or its parent, add it to the results array
		if ($file != '.' && $file != '..') $results[] = $file;
		
	}
	
	closedir($handler);
	
	return $results;
	
}

Usage:

$all_files = dirList($directory);

Method 3: While Loop

Yet another fine function for listing all files in a directory:

function shapeSpace_list_directory_files($dir) {
	
	if (is_dir($dir)) {
		if ($handle = opendir($dir)) {
			
			while (($file = readdir($handle)) !== false) {
				if ($file != "." && $file != ".." && $file != "Thumbs.db") {
					echo '<a href="'. $dir . $file .'">'. $file .'</a><br>'. "\n";
				}
			}
			
			closedir($handle);
			
		}
	}
}

Usage:

shapeSpace_list_directory_files($dir);

I forget the source of this one; if you happen to know, drop me a line.

★ Pro Tip:

USP ProSAC Pro