Ad Code

Ticker

6/recent/ticker-posts

PHP program to accept directory name and print its all subdirectories

 In this post, I have explained to access the directory and its subdirectory files using PHP programs and you can use this code in your projects if the project requires you to get a subdirectory of the directory.

PHP program to accept directory name and print its all subdirectories

Here is some function we can use to get the sub-directory list of the given directory.

  1. chdir():- This function is used to change the current directory.
  2. chroot():- This function is used to change the root directory.
  3. dir():- This function returns the instance of the directory class.
  4. is_dir():- This function to check the specified path is a directory or not.
  5. getcwd():- This function is used to get the returns of the current working directory.
  6. opendir():- This function is used to get the opens a directory handle.
  7. readdir():- This function is used to get the returns an entry from the directory handle.
  8. closedir():- This function is used to close the directory handle.
  9. rewinddir():- This function is used to resets the directory handle.
  10. scandir():- This function is used to get return an array of files and directories of the specific directory.
Here we are using opendir(), readdir() and is_dir() function to get the subdirectory of the specific directory using PHP program:-

<?php
 
// Set the directory path which you wants to get the sub directory
$dir = '../../';
 
// Initialize the variable to blank array
$subdir = [];
 
if( $handle = opendir($dir) ) { // open directory handle
     
    while( ($file = readdir($handle)) !== false ) { // read directory from directory handle
        if( !in_array($file, array('.', '..')) && is_dir($dir.$file)) // check is directory or not and remove the .,.. files in the directory to denote parent directory
            $subdir[]=$file;
    }
}
 
// Display result
echo "<pre>";
print_r($subdir);
echo "</pre>";
 
?>

In this program, we are use opendir() function to open the directory handle.

After the directory handle opens set the while loop to run when readdir() false to read every file and directory of the open handle directory.

inside while loop, we are checking the current file is . or .. and is a directory or not using is_dir() function.

If the condition is true then the file is a directory and the name is pushed in the $subdir variable and printed to a list of all sub-directory of the given directory.

Here we are describing only one method you can use another function to get the off files and directory in your program. You can also use it to get all files, all directory or files, and directory both.

Post a Comment

0 Comments

Ad Code