Find a file within any a specific folder with subfolders using PHP
I am stuck with the following, so any help would be appreciated.
I have a folder tree like follows:
images/collections/
Within the collections folder there 开发者_如何学JAVAcould be numerous subfolders
images/collections/collection1, images/collections/collection2
Images are named like
imageProductCode-something.jpg
What i am trying to do is pass one variable which is my product code to a script which then finds the file in any of the folders and returns its path...
images/collections/collection3/imageProductCode-something.jpg
You can use the RecursiveDirectoryIterator
function getImageDirectory($iId) {
$oDirectory = new RecursiveDirectoryIterator("/path/to/images/");
$oIterator = new RecursiveIteratorIterator($oDirectory);
foreach($oIterator as $oFile) {
if ($oFile->getFilename() == 'imageProductCode-' . $iId . '.jpg') {
return $oFile->getPath();
}
}
}
You could check all your collections:
$collections = array('collection1', 'collection2', 'collection3');
foreach ($collections as $collection) {
if (file_exists('/path/to/collections/'.$collection.'/'.$productCode.'.jpg')) {
... do your thing ...
break;
}
}
Depending on the size of your catalogue, it might be faster to create a database (flatfile or MySQL) to lookup the location of the image for a specific product code.
If you're using a version of PHP which is < 5.3, you might need to write the recursion yourself. Main methods your would like to follow:
- opendir
- readdir
- is_dir
- is_file
Start at the root of your images, check every entry. If it's a directory, check the directory. Seems like a lot of work, so if you're looking at large directories and image collections, you might want to look into either the unix command or db linking, as suggested above.
Another way would be to have the directories connected logically to the images, so that you can tell from the name (or other property) of the image in which directory to look.
Good luck,
Yishai
精彩评论