2

I`m trying to create a function that reads a directory and returns all file's working directories in an array, but it is not working. I don`t know why the code doesn`t work, can you help me?

$postsDirectory = "../posts/";

function listFiles() {
    $results = array();
    $handler = opendir($postsDirectory);

    while ($file = readdir($handler)) {
        if ($file != "." && $file != "..") {
            $results[] = getcwd($file);
        }
    }
    closedir($handler);
    return $results;
}

1 Answers1

0

getcwd() returns the working directory for the script that is being executed. It doesn't take any parameters, and it has nothing to do with other files on the file system (nor does the idea of a "working directory" make sense for an arbitrary file). I assume that what you actually want is a list of all directories within a given directory.

I would use a RecursiveDirectoryIterator for this:

$it = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($postsDirectory),
    FilesystemIterator::SKIP_DOTS
);

$results = array();
while($it->valid()) {
    if($it->isDir()) {
        $results[] = $it->getSubPath();
    }
    $it->next();
}
impl
  • 783
  • 5
  • 14