File Ops: An array containing file names within a directory

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dickey
Forum Commoner
Posts: 50
Joined: Thu May 16, 2002 8:04 pm
Location: Sydney, Australia

File Ops: An array containing file names within a directory

Post by dickey »

I have looked at the PHP file system commands, and I cannot see a function that would return an array of file names contained in a target directory.

A list of filenames i.e. ls on unix, or dir on windows.

Any advice would be greatly appreciated.

Thank you

- Dickey
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

http://www.php.net/manual/en/function.readdir.php
not returning an array of filenames but you will be able to create one.

also note http://www.php.net/manual/en/function.is-dir.php
rev
Forum Commoner
Posts: 52
Joined: Wed Oct 02, 2002 3:58 pm
Location: Atlanta, GA

Post by rev »

I'm feeling nice... :)

Per example 2 on http://www.php.net/manual/en/function.readdir.php this function will create an associative array of files in alphabetical order from a given directory.

Code: Select all

<?php
function getFileList($theDIR) {
	$fileArray = array();
	if($handle = opendir($theDIR)) {
		while(false !== ($file = readdir($handle))) {
			if($file != "." && $file != "..") {
				if(@is_file($theDIR . "/" . $file)) {
					$fileArrayї$file] = $theDIR . "/" . $file;
				}
			}
		}
		closedir($handle);
	}
	asort($fileArray);
	reset($fileArray);
	return $fileArray;
}

$fileListArray = getFileList("/path/to/dir");
?>
Post Reply