header

Free Script – PHP Directory Searcher

This function obtains a list of all of the files and sub-directories within a specified folder that is passed through as a parameter, this is ideal for image checking and file uploads.

//--------------------------------------------------------------------------------------------------------
// Function: BuildFileList
// Description: This function obtains a list of all of the files and sub-directories
// within a specIfied folder that is passwed through as a parameter, this is ideal
// for image checking and file uploads.
//--------------------------------------------------------------------------------------------------------

function BuildFileList($folder) {
	// Execute code If the folder can be opened, or fail silently
	if($contents = @ scandir($folder)) {
		// initialize an array for matching files
		$found = array();
		// Create an array of file types
		$fileTypes = array('doc','pdf','txt','docx','rtf','gIf','jpeg','jpg','png','avi','zip','mpeg','xml','bmp');
		// Traverse the folder, and add filename to $found array If type matches
		$found = array();
		foreach($contents as $item) {
			$fileInfo = pathinfo($item);
			if(array_key_exists('extension', $fileInfo) && in_array($fileInfo['extension'],$fileTypes)) {
				$found[] = $item;
			}
		}
		// Check the $found array is not empty
		if($found) {
			// Sort in natural, case-insensitive order, and populate menu
			natcasesort($found);
			foreach($found as $filename) {
				echo "<option value='$filename'>$filename</option>\n";
			}
		}
	}
}

Here is a simple implementation of the script that will output all the files in a directory:

BuildFileList("YOUR_DIRECTORY");
//Outputs: Files

Enjoy and Thanks to Marc Towler!

Random Posts

3 Responses to “Free Script – PHP Directory Searcher”

  1. Marc Towler Says:

    I am glad that you liked the tutorial :)

  2. omochan Says:

    hey AB. Nice job.

  3. Web Hosting Says:

    Thx, great tutorial :)

Leave a Reply