views:

153

answers:

6

Hi Guys,

I'm trying to design a program in PHP that would allow me to find files with specific file extensions (example .jpg, .shp etc) in a known directory which consists of multiple folders. Sample code, documentation or information about what methods I will be required to use will be much appreciated.

+3  A: 

glob is pretty easy:

<?php
foreach (glob("*.txt") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}
?>

There are a few suggestions for recursive descent at the readdir page.

Ewan Todd
+1  A: 

I believe PHP's glob() function is exactly what you are looking for:

http://php.net/manual/en/function.glob.php

eyazici
+6  A: 

Take a look at PHP's SPL DirectoryIterator.

dnagirl
+1 Excellent! I'd overlooked the SPL. The OP should probably get familiar with some of the basic stuff first, though.
Ewan Todd
If learning PHP, the SPL is a great place to start, as there is far more win there than in PHP's legacy, inconsistent function library.
Lucas Oman
A: 

Use readdir to get a list of files, and fnmatch to work out if it matches your required filename pattern. Do all this inside a function, and call your function when you find directories. Ask another question if you get stuck implementing this (or comment if you really have no idea where to start).

Dominic Rodger
A: 

Here's a nice tutorial that will walk you through the steps. The second post provides you with a class that extends the search function to take a keyword.

Hopefully this is a good starting point to what your looking for.

Shane
A: 

glob will get you all the files in a given directory, but not the sub directories. If you need that too, you will need to: 10. get recursive, 20. goto 10.

Here's the pseudo pseudocode:

function getFiles($pattern, $dir) {
    $files = glob($dir . $pattern);
    $folders = glob($dir, GLOB_ONLYDIR);
    foreach ($folders as $folder) {
        $files = $files + getFiles($folder);
    }
    return $files;
}

The above will obviously need to be tweaked to get it working, but hopefully you get the idea (remember not to follow directory links to ".." or "." or you'll be in infinite loop town).

nickf