Given the path of the folder and the task is to print the names of subfolders and files present inside them.
Explanation: In our PHP code, initially, it is checked whether provided path or filename is a directory or not using the is_dir() function. Now, we open the directory using opendir() function and then check whether it is getting opened or has some errors. Then we use a while loop to get the names of all the subfolders, as well as files, present inside the directory with the help of readdir() function. Now we are going inside each subfolder and reading the names of all the files present inside them following a similar procedure.
Folder Structure:

Code:
Note: This Code have been saved as PHP file and accessed through wampserver
php
<?php
$gfg_folderpath = "GeeksForGeeks/" ;
if ( is_dir ( $gfg_folderpath )) {
$files = opendir( $gfg_folderpath ); {
if ( $files ) {
while (( $gfg_subfolder = readdir( $files )) !== FALSE) {
if ( $gfg_subfolder != '.' && $gfg_subfolder != '..' ) {
echo "SUBFOLDER--" . $gfg_subfolder . "<br>
"." Files in ".$gfg_subfolder." --<br>";
$dirpath = "GeeksForGeeks/" . $gfg_subfolder . "/" ;
if ( is_dir ( $dirpath )) {
$file = opendir( $dirpath ); {
if ( $file ) {
while (( $gfg_filename = readdir( $file )) !== FALSE) {
if ( $gfg_filename != '.' && $gfg_filename != '..' ) {
echo $gfg_filename . "<br>" ;
}
}
}
}
}
echo "<br>" ;
}
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>What's there in GeeksForGeeks </title>
</head>
<body>
</body>
</html>
|
Output:
