Search code examples
phpreaddir

Read Dir PHP class - only 1 file by return


I´m trying to write and use php classes. This is my class:

class UseDir
{

    public $varReadFilesFromDir;        

    public function readDir(){

        if (is_dir($this->varReadFilesFromDir)) 
        {
            if ($dirHandler = opendir($this->varReadFilesFromDir)) 
            {
                while (($getFile = readdir($dirHandler)) !== false) 
                {
                    if($getFile != "." && $getFile != ".."){

                        if (strpos($getFile, '.xml') === false){

                            continue;
                        }

                        //echo "<p>$getFile</p>";
                        //return $getFile;

                    }
                }
            }
            closedir($dirHandler);
        }
    }

}

$new_UseDir = new UseDir();

$new_UseDir->varReadFilesFromDir = "C:\dir\files";

$new_UseDir->readDir();

I want to get each file here and want to use another class where i can do something with the file, later. If i uncomment //echo "<p>$getFile</p>"; it shows all file Names.

If i uncomment //return $getFile; and edit echo $new_UseDir->readDir(); it shows only the first file from the directory.

Why i get only 1 File?

regards, ebody


Solution

  • You will only get one file, because readdir only returns one file name per call. If you want all files in the directory, you have to store each returned file name in - let's say - an array and return that array instead.