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);
	}
}


Written by: Dag Jonny Nedrelid
©2007-2012 http://thronic.com


Feel free to leave a comment.
Name:
URL:
0