learn

Recursive Directory Listing

category: Snippets
Created by: Assaad Youssef Abou-Rached

Recursive Directory Listing

category: Snippets
Created by: Assaad Youssef Abou-Rached
twitter google+ facebook pinned 

Recursive Directory Listing

Scan directory and list its content (folders, subfolders, and files)

Built-in functions to be used: is_dir(), opendir(), readdir(), closedir()
Built-in constants to be used: DIRECTORY_SEPARATOR

We will build a simple function that scans a given directory and loop through its content recuresivly, saving its content
to an array and return the array.

Steps:

  1. Open the given directory using opendir() function and save the data in a variable
  2. Loop through the contents while reading each chunk using readdir() function
  3. Exclude '.' and '..' levels from content
  4. Check if the current object is a directory, if so we will save its name in an associative array and loop recursively through it to scan for subdirectories and files; if it is a file we will simply save it in the array
  5. Once the loop is done, we will close the handle using closedir() function
  6. Last but not least, we will return the array