How to list files in a directory using PHP

Using this simple snippet, you can easily get files in a directory as an array. It even allows file type filters.

function stf_get_files( $directory, $filter = array( "*" ) ){
	$results = array(); // Result array
	$filter = (array) $filter; // Cast to array if string given

	// Open directory
	$handler = opendir( $directory );

	// Loop through files
	while ( $file = readdir($handler) ) {

		// Jump over directories.
		if( is_dir( $file ) )
			continue;
	
		// Prepare file extension
		$extension = end( explode( ".", $file ) ); // Eg. "jpg"
		
		// If extension fits add it to array
		if ( $file != "." && $file != ".." && ( in_array( $extension, $filter ) || in_array( "*", $filter ) ) ) {
			$results[] = $file;
		}
	}

	// Close handler
	closedir($handler);

	// Return
	return $results;
}

Usage:

  // Sample 
  $theme_dir = get_stylesheet_directory();  
  $theme_files = stf_get_files( $theme_dir, array( "php", "css", "txt" ) );
  
  print_r( $theme_files );

Output:

Array ( [0] => functions.php [1] => header.php [2] => style.css )

Enjoy!

Related Posts

NS Weight Release

WP-Backgrounds Lite by InoPlugs Web Design and Juwelier Schönmann 1010 Wien