Nate
Nate

Reputation: 259

php scandir() not showing files - only showing directories

I have a directory structure as follows:

/files
/files/001
/files/001/addfile.php
/files/002
/files/002/deletefile.php
/files/003
/files/003/viewfile.php

My script:

error_reporting(E_ALL);
$directory      = 'files';
$files      = scandir($directory);

$xml = new DOMDocument('1.0', 'UTF-8');
$xmlFiles = $xml->appendChild($xml->createElement('FILES'));
if(is_dir($directory)) {
    print_r($files);
}
/*foreach($files as $file => $key) {
    if($file == '.' || $file == '..') { continue; }
    echo '$file: '.$file;
    if(is_dir("$directory/$file")) {
        $xmlDir->appendChild($xml->createElement($file));
    }
    else {
        $xmlFiles->appendChild($xml->createElement('FILE', $file));
    }
}*/
echo $xml->saveXML();

My problem: The print_r($files) outputs:

Array ( [0] => . [1] => .. [2] => 001 [3] => 002 [4] => 003 )

How come scandir only outputs the directories and not the files?

TIA, Nate

Upvotes: 3

Views: 2658

Answers (3)

user1645055
user1645055

Reputation:

you can use RecursiveIteratorIterator for get directory with sub directory listing

Here is how to empty a directory using iterator:

<?php
function empty_dir($dir) {
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir),
                                             RecursiveIteratorIterator::CHILD_FIRST);
   foreach ($iterator as $path) {
     if ($path->isDir()) {
        // do something with directory
        //    rmdir($dir);
     } else {
       //doo something with files 
       // unlink($path->__toString());
     }
   }
  //    rmdir($dir);
}
?>

Upvotes: 2

Nate
Nate

Reputation: 259

Scandir does not work recursively. It only scans the path input into it.

Scandir Recurrsive function to scan deeper into the file system

Upvotes: 3

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

your files are in these directories, and scandir shows just content of specified path, but without any recurrency, so all is correct.

Upvotes: 5

Related Questions