list_directory()
public function list_directory(string $directory_path, bool $recursive = false): array
Description
Lists all files and directories within a specified path. Returns a simple array of names for flat listings, or a nested array structure when using recursive mode to traverse subdirectories.
Understanding Paths: The list_directory() method works with paths relative to your application's root directory. The method includes built-in security validation to prevent "directory traversal" attacks or access to sensitive areas like config or engine.
Parameters
| Parameter | Type | Description |
|---|---|---|
| $directory_path | string | The relative path to the directory whose contents should be listed. |
| $recursive | bool | (optional) If true, includes all subdirectories and their contents in a nested array structure. Default is false. |
Return Value
| Type | Description |
|---|---|
| array | A simple array of names when $recursive is false, or a nested associative array when $recursive is true. |
Understanding the Return Structure
The structure of the returned array changes significantly based on the $recursive parameter. Understanding this difference is key to processing the data correctly.
1. Non-Recursive Mode (Flat List)
This is the default mode. It returns a simple, numerically indexed array of strings. Crucially, it does not distinguish between a file and a folder.
2. Recursive Mode (Nested Tree)
In recursive mode, the array becomes associative. Directories are represented as keys (strings) pointing to their own arrays of content. Files remain as values with numeric keys.
Comprehensive Examples
Example 1: Building a Dynamic File Browser
Since flat listings don't differentiate types, we use PHP's is_dir() to build a more informative list.
Example 2: Recursive File Search
This pattern demonstrates how to traverse the nested array returned by a recursive listing to find specific file types.
The "Check Before You Act" Pattern
Always wrap your directory listings in a try/catch block or use $this->file->exists() beforehand. The list_directory() method will throw an exception if the path is invalid, restricted, or simply doesn't exist. Defensive programming ensures your application remains stable even if a folder is deleted manually from the server.