Tips : Easy way to find a file in subdirectory with php
I’ve made a previus post on SPL using RecursiveIterator to parse Array. Today we will use this same RecursiveIterator with a DirectoryRecursiveIterator.
We have a directory with a lot of subdirectory like this and we want to find this file
:

So we are just executing a page which must include the file_to_find.php :
include(dirname(__FILE__)."/class.directorysearch.php"); directory = dirname(__FILE__)."/directory"; $search_directory = new DirectorySearch($directory); path_file = $search_directory->find("file_to_find.php"); if($path_file !== false){ include_once($path_file); }
Let’s have a look to the class.directorysearch.php :
class DirectorySearch { private $iterator, $directoryname; public function __construct($directoryname){ $this->iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directoryname,RecursiveDirectoryIterator::KEY_AS_FILENAME)); } public function find($filename){ foreach($this->iterator as $entry){ if($filename == $this->iterator->current()){ return $this->iterator->getPathName(); } } return false; } }
If we don’t use the KEY_AS_FILENAME with the recursiveDirectoryIterator we will have the whole path of the file in $this->iterator->current();
All of this is a basic example of the RecursiveIteratorIterator with the RecursiveDirectoryIterator. SPL is a very powerfull toolkit !
Edit : http://blog.makemepulse.com/2008/02/19/tips-find-a-file-in-subdirectory-with-filteriterator-in-php/


6 Comments
Jump to comment form | comments rss [?] | trackback uri [?]