开发者

Searching for specific file extensions in a folder/directory (PHP)

I'm trying to design a program in PHP that would allow me to find 开发者_如何学Pythonfiles 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.


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.


Take a look at PHP's SPL DirectoryIterator.


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

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


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).


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).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜