Retrieving Subdirectories Using PHP
In PHP, you may encounter the need to access all subdirectories within a specific directory, excluding root and directory traversal indicators. Here's how you can achieve this using two different approaches.
Option 1: Utilizing glob()
The glob() function provides a straightforward way to list files and directories matching a specific pattern. To retrieve only subdirectories, use it with the GLOB_ONLYDIR option:
$subdirectories = glob('*/*', GLOB_ONLYDIR);
Option 2: Employing array_filter
array_filter allows you to filter an array based on a callback function. You can use it to identify subdirectories by excluding "." and ".." and filtering the glob() results:
function is_subdirectory($item) { return is_dir($item) && $item != '.' && $item != '..'; } $subdirectories = array_filter(glob('*'), 'is_subdirectory');
Usage in a Function
Once you have the array of subdirectories, you can pass it to a function for further processing. For instance, the following function prints the paths of all subdirectories:
function print_subdirectory_paths($subdirectories) { foreach ($subdirectories as $subdirectory) { echo $subdirectory . PHP_EOL; } }
The above is the detailed content of How to Retrieve Subdirectories in PHP, Excluding Root and Directory Traversal Indicators?. For more information, please follow other related articles on the PHP Chinese website!