Home > Backend Development > PHP Tutorial > How to Retrieve Subdirectories in PHP, Excluding Root and Directory Traversal Indicators?

How to Retrieve Subdirectories in PHP, Excluding Root and Directory Traversal Indicators?

Linda Hamilton
Release: 2024-11-14 14:35:02
Original
980 people have browsed it

How to Retrieve Subdirectories in PHP, Excluding Root and Directory Traversal Indicators?

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);
Copy after login

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');
Copy after login

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;
  }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template