开发者

PHP - Open or copy a file when knowing only part of its name?

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 the开发者_Python百科n 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?


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.


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.


$result = system("ls \server\" . $specialNumber . '\');
$fh = fopen($result, 'r');


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜