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.
Here is some function we can use to get the sub-directory list of the given directory.
- chdir():- This function is used to change the current directory.
- chroot():- This function is used to change the root directory.
- dir():- This function returns the instance of the directory class.
- is_dir():- This function to check the specified path is a directory or not.
- getcwd():- This function is used to get the returns of the current working directory.
- opendir():- This function is used to get the opens a directory handle.
- readdir():- This function is used to get the returns an entry from the directory handle.
- closedir():- This function is used to close the directory handle.
- rewinddir():- This function is used to resets the directory handle.
- scandir():- This function is used to get return an array of files and directories of the specific directory.
<?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.
0 Comments