Friday, 3 June 2016

PHP- LIST ALL DIRECTORIES/FOLDERS FROM A SPECIFIED LOCATION

This is a quick extension/counterpart to my existing blog post that explains how to List All Files In A Directory in PHP. But instead of listing all files, I’m quickly going to jot down how to list all directories/folders in a specified location.
Someone had asked in the comments section how to do it, so I thought I’d quickly write a blog post about it. It’s actually not much different from the code I used to list all files in a directory- all that’s required is an extra function, is_dir. The PHP code is very simple and only requires a small amount of code. I’ve seen a lot of examples on other forums/websites that use a ridiculous amount of code to get the same result, and i’m not quite sure why.

Here’s how to list all files in a directory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//path to directory to scan
$directory = "index_files/";
 
//get all files in specified directory
$files = glob($directory . "*");
 
//print each file name
foreach($files as $file)
{
 //check to see if the file is a folder/directory
 if(is_dir($file))
 {
  echo $file;
 }
}

0 comments:

Post a Comment