Recursive file searching function in PHP
What is a recursive function?
A recursive function is basically just a function that calls itself from within, making several instances of itself until you force it to stop. It’s good for when you don’t have a definitive concept depth to deal with, like searching for files through subdirectories, but don’t know how many directories and files there may be.
Here’s a recursive function I’ve made to search for images. It takes a search word and the folder to search in as first and second parameters.
// Recursive search function, a bit scary... I hope it won't make the universe implode on itself function searchEngine($keyword, $folder) { global $SearchedImagesFoundCount, $SearchedImages; if($handle = opendir($folder)) { while(($file = readdir($handle)) !== false) { if((stristr($file,'.jpg') !== false || stristr($file,'.gif') !== false || stristr($file,'.png') !== false) && stristr($file,$keyword) !== false) { $SearchedImagesFoundCount += 1; array_push($SearchedImages,$folder.'/'.$file); } elseif(is_dir($folder.'/'.$file) && $file != '.' && $file != '..') { // Ran into a folder, we have to dig deeper now searchEngine($keyword,$folder.'/'.$file); } } closedir($handle); } }
This is a stripped down version that might be easier to understand. This would simply search for a file (first parameter) in the given directory (second parameter).
function searchEngine($keyword, $folder) { if($handle = opendir($folder)) { while(($file = readdir($handle)) !== false) { if(stristr($file,$keyword) !== false) { // Action when a filename matching $keyword is found. } elseif(is_dir($folder.'/'.$file) && $file != '.' && $file != '..') { // Ran into a folder, we have to dig deeper now searchEngine($keyword,$folder.'/'.$file); } } closedir($handle); } }
Leave a Reply
Welcome to Thronic.com
Search this Site
Miscellaneous Links
Recent Articles
- Google-like search suggestion tool
- Linux Bash Color
- Resize a div layer with javascript
- Moving a div layer with javascript
- Web Galaxy » A sci-fi browser game
- Windows 7 on Asus Eee 900 PC
- IE and PHP sessions
- Wordpress 2.8.6 Spell Check Languages
- Reset MySQL Root Password
- Linux hosts file
- IdleGuard
- Column count in SQL
- String encryption in PHP
- Alphanumeric Captcha values in PHP
- Your own numeric Captcha in PHP
