alegig
alegig

Reputation: 3

distinguish file and directory in PHP

my problem is a php page that extracts the contents of a directory.
As you can see in the snippet below, the path is passed via GET.
The first time I call the page reads everything correctly, but if you just read the folder contains a sub-directory, it is recognized as a file.
Do you have any advice or solution?
thanks

 <?php
     $path = $_GET['dir'];
     function createDir($path) {
         if ($handle = opendir($path)) {
             echo "<ul>";
             while (false !== ($file = readdir($handle))) {
                 if (is_dir($path . $file) && $file != '.' && $file != '..')
                     printSubDir($file, $path, $queue);
                 else if ($file != '.' && $file != '..')
                     $queue[] = $file;
             }

             printQueue($queue, $path);
             echo "</ul>";
         }
     }

     function printQueue($queue, $path) {
         foreach ($queue as $file) {
             printFile($file, $path);
         }
     }

     function printFile($file, $path) {
         echo "<li>";
            // print a file
         echo "</li>";
     }

     function printSubDir($dir, $path) {
         echo "<li>";
            // print a directory
         echo "</li>";
     }

     createDir($path);
 ?>

Upvotes: 0

Views: 496

Answers (2)

Wesley van Opdorp
Wesley van Opdorp

Reputation: 14941

you could use the DirectoryIterator to easily achieve this:

$oIterator = new DirectoryIterator(dirname(__FILE__));
foreach ($oIterator as $oFileInfo) {

    // Either . or ..
    if ($oFileinfo->isDot()) {

    }

    // A directory
    if ($oFileInfo->isDir()) {

    }
}

Upvotes: 3

JNDPNT
JNDPNT

Reputation: 7465

You can use is_dir() or is_file() to check this and than use recursive functions to read those as well. If it's just to mark is as a directory you can just use the check.

http://php.net/manual/en/function.is-dir.php

Upvotes: 1

Related Questions