Jump to content

Best way to list files in a directory by extension


guyfromfl

Recommended Posts

I have a script that works perfectly, for one type of file extension.

 

What I want to do now is be able to list all files in a set of file types.

 

I want to pass the argument to the fileSystem class's loadFiles method like this:

 

$some_var = $fileSystem->loadFiles(DATA_DIRECTORY, "csv,xls,etc");

 

Then in the loadFiles method it reads the dir for each file, then test its extension.  If they are of the right type, then push it on the returned array.

 

Now I am having problems testing if the file's extension is in the array.  If I use

 

if (strpos(getExt($file),  $array_of_wanted_exts))...

 

php would match php3..

 

Does anybody have a better method?

Link to comment
Share on other sites

class RecursiveFileExtensionFilterIterator extends RecursiveFilterIterator
{
    private $validFileExtensions = array();
    
    public function __construct($recursiveIterator, $validFileExtensions) {
        $this->validFileExtensions = $validFileExtensions;
        
        parent::__construct($recursiveIterator);
    }
    
    public function accept() {
        return in_array(pathinfo($this->current(), PATHINFO_EXTENSION), $this->validFileExtensions);
    }
}

foreach(new RecursiveFileExtensionFilterIterator(new RecursiveDirectoryIterator('.'), array('php')) as $file) {
    echo $file->getFilename(), "\r\n";
}

Link to comment
Share on other sites

That is sexy, but I would go for simpler.  Either pass in an array of file extensions, or explode for one and use in_array() if you're looping through a directory with readdir() or some such.  But I would probably glob():

 

function loadFiles($directory, $extensions) {
    $pattern = '{*.' . implode(',*.', explode(',', $extensions)) . '}';
    return glob($directory . '/' . $pattern, GLOB_BRACE);
}
$some_var = loadFiles(DATA_DIRECTORY, "csv,xls,etc");

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.