Uncategorized

Searching File Within Directory Recursively Using PHP Scandir Function

Oleh takien• 3 Komentar Arsip

Recently I had to find my file stored somewhere in my server. Although I can do this easily using the built-in feature in cPanel File Manager, but what I need is to search file programaticallyusing a script. So, I created this function.

function find_file($dirs,$filename,$exact=false){

	$dir = @scandir($dirs);
	if(is_array($dir) AND !empty($dir)){
	foreach($dir as $file){
	if(($file !== '.') AND ($file!=='..')){
	if (is_file($dirs.'/'.$file)){
		$filepath =  realpath($dirs.'/'.$file);

		if(!$exact){
			$pos = strpos($file,$filename);
			if($pos === false) {
			}
			else {
				if(file_exists($filepath) AND is_file($filepath)){
				echo str_replace($filename,'<span style="color:red;font-weight:bold">'.$filename.'</span>',$filepath).' ('.round(filesize($filepath)/1024).'kb)<br />';
				}
			}
		}
		elseif(($file == $filename)){

			if(file_exists($filepath) AND is_file($filepath)){
				echo str_replace($filename,'<span style="color:red;font-weight:bold">'.$filename.'</span>',$filepath).' ('.round(filesize($filepath)/1024).'kb)<br />';
			}
		}
	}
	else{
		find_file($dirs.'/'.$file,$filename,$exact);
	}
	}
	}
	}
}

The function accepts three parameters:

  1. $dir (string), absolute path of the directory to start the search, to use current directory use dirname(__FILE__).
  2. $filename (string), the keyword to search for.
  3. $exact (bool), true/false, default is false. If you set it to true it will find the exact ‘index.php’ not ‘anotherindex.php’ for keyword ‘index.php’.

How to use this function?

This will find all file name contains content within current directory and all it’s sub directories.

< ?php find_file(dirname(__FILE__),'content');
?>

And the search result will be like this:

Search file using PHP functions

Search file using PHP functions

Another Approach

Another way to search file in directory is using PHP glob function, as written here.

Tulisan ini sudah berumur: 14 tahun 10 bulan 11 hari. Informasi di dalamnya mungkin sudah tidak relevan, tapi nilai historisnya sangat berharga, terutama bagi saya sebagai penulisnya.

Komentar (3)

Arsip Statis
Prahastu
top
TionTux
thanks for the information, this is exactly what I was looking for.
tamil
nice