list_files() WordPress Function

The list_files() function is used to list all files in a directory. It takes two parameters: the directory path and an optional recursive flag. If the recursive flag is set to true, the function will list all files in the specified directory and all subdirectories.

list_files( string $folder = '', int $levels = 100, string[] $exclusions = array() ) #

Returns a listing of all files in the specified folder and all subdirectories up to 100 levels deep.


Description

The depth of the recursiveness can be controlled by the $levels param.


Top ↑

Parameters

$folder

(string)(Optional) Full path to folder.

Default value: ''

$levels

(int)(Optional) Levels of folders to follow, Default 100 (PHP Loop limit).

Default value: 100

$exclusions

(string[])(Optional) List of folders and files to skip.

Default value: array()


Top ↑

Return

(string[]|false) Array of files on success, false on failure.


Top ↑

Source

File: wp-admin/includes/file.php

function list_files( $folder = '', $levels = 100, $exclusions = array() ) {
	if ( empty( $folder ) ) {
		return false;
	}

	$folder = trailingslashit( $folder );

	if ( ! $levels ) {
		return false;
	}

	$files = array();

	$dir = @opendir( $folder );

	if ( $dir ) {
		while ( ( $file = readdir( $dir ) ) !== false ) {
			// Skip current and parent folder links.
			if ( in_array( $file, array( '.', '..' ), true ) ) {
				continue;
			}

			// Skip hidden and excluded files.
			if ( '.' === $file[0] || in_array( $file, $exclusions, true ) ) {
				continue;
			}

			if ( is_dir( $folder . $file ) ) {
				$files2 = list_files( $folder . $file, $levels - 1 );
				if ( $files2 ) {
					$files = array_merge( $files, $files2 );
				} else {
					$files[] = $folder . $file . '/';
				}
			} else {
				$files[] = $folder . $file;
			}
		}

		closedir( $dir );
	}

	return $files;
}


Top ↑

Changelog

Changelog
VersionDescription
4.9.0Added the $exclusions parameter.
2.6.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.