Ad Code

Ticker

6/recent/ticker-posts

How to print sub-directories in PHP program


There have many predefined functions use to get directory files and subdirectories, but here we are disclosing some useful methods to get directory or file from given directory paths.

scandir(path, order, context):-

List files and directories inside the specified path,

$dir = "/images/";

// Sort in ascending order - this is default
$a = scandir($dir);

// Sort in descending order
$b = scandir($dir,1);

print_r($a);
print_r($b);

Array
(
[0] => .
[1] => ..
[2] => bol.gif
[3] => dog.gif
[4] => elephant.gif
)
Array
(
[0] => elephant.gif
[1] => dog.gif
[2] => bol.gif
[3] => ..
[4] => .
)
here scandir have two examples one in ascending order and another in descending order. scandir print all files and subdirectory names in the list.

readdir():-
The readdir() function returns the name of the next entry in a directory. In readdir function usage with opendir() which is opens up a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls. 
  $dir = "/images/";

// Open a directory, and read its contents
if (is_dir($dir)){
  if ($dh = opendir($dir)){
    while (($file = readdir($dh)) !== false){
      echo "filename:" . $file;
    }
    closedir($dh);
  }
}

Result

filename: bol.gif
filename: dog.gif
filename: elephant.gif
  
this handles only files that means its allow to read-only directory contents.

glob():-
This function uses to find pathnames matching patterns.

here is the example to show the only text file inside the directory.

print_r(glob("*.txt"));
    
Array (
  [0] => target.txt
  [1] => source.txt
  [2] => test.txt
  [3] => test2.txt
)
The glob() function used to file a specific file that matches the pattern here use to a specific function to find the only directory in many ways, but I have described only one method which is very easy to use.

$dirs = array_filter(glob('*'), 'is_dir');
print_r($dirs);

Result:-

Array(
 [0] => images
 [1] => document
 [2] => projects
)

Post a Comment

0 Comments

Ad Code