Search Directory by PHP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mehdi110
Forum Newbie
Posts: 1
Joined: Tue Feb 26, 2008 4:40 am

Search Directory by PHP

Post by mehdi110 »

i used this code to Search directory

Code: Select all

<?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 customize it so that Subdirectories also be searched too...
User avatar
EverLearning
Forum Contributor
Posts: 282
Joined: Sat Feb 23, 2008 3:49 am
Location: Niš, Serbia

Re: Search Directory by PHP

Post by EverLearning »

You could put this code in a function make it call itself when it encounters a directory(recursive functions). Here's an example(taken from folowing article: Recursion In PHP: Tapping Unharnessed Power)

Code: Select all

 
$delim = strstr(PHP_OS, "WIN") ? "\\" : "/";
 
function retrieveTree($path)  {
    global $delim;
 
    if ($dir=@opendir($path)) {
        while (($element=readdir($dir))!== false) {
            if (is_dir($path.$delim.$element) && $element!= "." && $element!= "..") {
                $array[$element] = retrieveTree($path.$delim.$element);
            } elseif ($element!= "." && $element!= "..") {
                $array[] = $element;
            }
        }
        closedir($dir);
    }
    return (isset($array) ? $array : false);
}
 
If you have PHP5 at your dispoal, i suggest you also read this article:
Iterators in PHP5
Post Reply