Jump to content

Search Directory by PHP


mehdi110

Recommended Posts

i used this code to Search directory

 

<?php
if ($handle = opendir('./')) {
while (false !== ($file = readdir($handle))) {
    $filesplit = explode(".", $file);
    $check = $filesplit[0];
$keyword=$_GET['search'];
if(ereg($keyword, $check))
      {
         $check .= ".$filesplit[1]";
         $valid[] = $check;
      }
}
for($index = 0; $index < count($valid); $index++)
{
  echo"<br>$valid[$index]";
}
closedir($handle);

}
?>

 

but it only search the main directory, not the Subdirectories.... can someone please tell how to search all subdirectories too....

Link to comment
https://forums.phpfreaks.com/topic/92920-search-directory-by-php/
Share on other sites

Haven't tested this, but I think it should do the job.

 

<?php

//Searches recurisvely for $keyword in a given folder and it's subfolders
function search_files ($keyword, $dir = ".")
{
$files = array();
if (!$handle = opendir($dir.'/'))
	return $files;
while ($file = readdir($handle))
{
	if($file == "." ||  $file == "..")
		continue;
	if(is_dir($file))
		$files = array_merge(search_files($file), $files);
	else
	{
		$no_ext = substr($file, 0, strrpos($file, '.') - strlen($file)); //remove extension
		if(strpos($no_ext, $keyword) !== FALSE)
			$files[] = $file;
	}
}
closedir($handle);

return $files;
}

$files = search_files("keyword");
foreach($files as $file)
echo $file."<br>";

?>

 

 

Orio.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.