tags:

views:

45

answers:

4

I have a huge repository of files that are ordered by numbered folders. In each folder is a file which starts with a unique number then an unknown string of characters. Given the unique number how can i open or copy this file?

for example: I have been given the number '7656875' and nothing more. I need to interact with a file called '\server\7656800\7656875 foobar 2x4'.

how can i achieve this using PHP?

+3  A: 

If you know the directory name, consider using glob()

$matches = glob('./server/dir/'.$num.'*');

Then if there is only one file that should start with the number, take the first (and only) match.

Yacoby
You've left out a single quote to the left of `.$num`.
nikc
Wow, nice! I can honestly say i've never used glob ever! Thanks, i've learned something very valuable.
Gary Willoughby
A: 
$result = system("ls \server\" . $specialNumber . '\');
$fh = fopen($result, 'r');
Zachary Burt
A: 

If it's hidden below in sub-sub-directories of variable length, use find

echo `find . -name "*$input*"`;

Explode and trim each result, then hope you found the correct one.

Tim Green
+2  A: 

Like Yacoby suggested, glob should do the trick. You can have multiple placeholders in it as well, so if you know the depth, but not the correct naming, you can do:

$matchingFiles = glob('/server/*/7656875*');

which would match

"/server/12345/7656875 foo.txt"
"/server/56789/7656875 bar.jpg"

but not

"/server/12345/subdir/7656875 foo.txt"

If you do not know the depth glob() won't help, you can use a RecursiveDirectoryIterator passing in the top most folder path, e.g.

$iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator('/server'));

foreach($iterator as $fileObject) {
    // assuming the filename begins with the number
    if(strpos($fileObject->getFilename(), '7656875') === 0) {
         // do something with the $fileObject, e.g.
         copy($fileObject->getPathname(), '/somewhere/else');
         echo $fileObject->openFile()->fpassthru();
    }
}

* Note: code is untested but should work

DirectoryIterator return SplFileInfo objects, so you can use them to directly access the files through a high-level API.

Gordon
I don't have the karma to edit your answer so will note that the above code (at the time of writing this) will not work as expected due to a typo on the `strpos` line. Feel free to remove this comment if/when the typo is no longer there. :-)
salathe
@salathe thanks. corrected. Comments can only be removed by moderators.
Gordon
Gordon, no worries. Other useful Iterators for this question would be: [`GlobIterator`](http://php.net/globiterator), to get the best of both worlds; or the [[`Recursive`](http://php.net/recursiveregexiterator)] [`RegexIterator`](http://php.net/regexiterator), to be even more specific about which files to glob.
salathe