Kavya Shree Kavya Shree - 14 days ago 5
PHP Question

Get filename from each folder (like nested) using PHP

My directory Structure is like

car_brands/AAA/alto.php
car_brands/BBB/figo.php
car_brands/CCC/beat.php


PHP Code

<?php
$dir = "Car_Brands";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh)))
{
$files[] = $filename;
}
natcasesort($files);
foreach ($files as $file)
{
if($file!='.' && $file!='..')
{
echo $file;
}
}
?>


Like I want

<a href="Car_Brands/<?php echo $file; ?>/"here i want filename of particular folder"" class="btn btn-red" style="width:180px;height:50px;"><br/><?php echo $file; ?><br/></a>


By This code I can get folders under car_brands.like AAA,BBB,CCC but how can get the php filename under each folder in single foreach loop is there any easy way to do this.

Answer

you can use scandir to get the list of all files in a given directory.

So, your code be changed like this:

         $dir = "Car_Brands";  
         $dh  = opendir($dir);  
         while (false !== ($subdir = readdir($dh))) 
         {   
             $fileList = scandir($dir.'/'.$subdir);
             $files[] = $fileList[2];  
         }  
         natcasesort($files); 
         foreach ($files as $file) 
         {
            if($file!='.' && $file!='..')   
            {  
                 echo $file;
            } 
         }

scandir() returns an array that contains the list of all the files in the given directory. If you are in linux server and you are sure each of your directory has one file only, you should get your file name from the 3rd index of the Array, which is $fileList[2] in our case. It is the 3rd index cause if you do a var dump of the array that scandir() returns you will see something like below:

Array
(
    [0] => .
    [1] => ..
    [2] => alto.php
)

I would recommend you to do a print_r($fileList) within your loop, that will give you a better idea on what index to look at.

Update

You can also use glob. In that case your code will look like the below:

         $dir = "Car_Brands";
         $dh  = opendir($dir);
         while (false !== ($dirname = readdir($dh)))
         {
             if ($dirname == '..' || $dirname == '.') {
                 continue;
             }
             $subdir = $dir.'/'.$dirname.'/';
             $ext = '*.php';
             $fileList = glob($subdir.$ext);
             if (!empty($fileList)) {
                 $files[] = $fileList[0];
                 // The above line will return the whole path. (eg. car_brands/AAA/alto.php)
                 // if you want the file name only (eg. alto.php) use the below line instead
                 // $files[] = str_replace($subdir, '', $fileList[0]);
             }
         }
         natcasesort($files);
         foreach ($files as $file)
         {
             echo $file;
         }
Comments