Zend - The PHP Company




Files and Directories

Add Code


File Search  

Type: code fragment
Added by: dwebb
Entered: 26/09/2000
Last modified: 01/12/2000
Rating: - (fewer than 3 votes)
Views: 7222
This function allows your script to search through a directory tree for a file. The search is depth first. The fully qualified file name is returned if the file is found.


<?php

// Purpose:  Find a file in a directory tree.
// Author:   Douglas P. Webb
// Revision: 1.0.1
// If you make improvements : Please e-mail dwebb@cetac.com
//
// filefind accepts two parameters:
//  $basedirectory : The root of the directory tree to search
//  $needle        : The file to find
//
// Return Value: 
//   The fully qualified file name of the target file if it is found,
//   if the target file cannot be found then an empty string is returned.
//
// Sample Usage:
//   $fullpath = filefind($DOCUMENT_ROOT, "scriptEngine.php");
//   if ($fullpath != "")
//     { Some processing (presumably involving scriptEngine.php) }
//
//  NOTE: The search is case sensitive (because UNIX is) 

// This construct is to prevent the same include file from being included more than once,
//    lest it bloat the code.
if (!defined("__DLIB_FILEFIND_DEFINED")) 
  {
  
define('__DLIB_FILEFIND_DEFINED'TRUE);
 
  function 
filefind ($basedirectory$needle
     { 
     
$handle=opendir($basedirectory);
     while (
$file readdir($handle))
       {
       if ((
$file == ".") || ($file == ".."))
         continue;
       
       if (
is_dir($basedirectory '/' $file))
         {
         
$subDirResult filefind($basedirectory '/' $file$needle);
         if (
$subDirResult != "")
           {
           
closedir($handle);
           return 
$subDirResult;
           }
         }   
//  if (is_dir($file))

       
if (strcmp($file$needle) == 0)
         {
         
closedir($handle);
         return 
$basedirectory '/' $needle;
         }

       }   
// while ($file = readdir($handle))
     
closedir($handle);
     return 
""
     }  
//  function filefind
  
}
?>


Usage Example


$fullpath = filefind($DOCUMENT_ROOT, "scriptEngine.php");
   if ($fullpath != "")
     { Some processing (presumably involving scriptEngine.php) }


Rate This Script





Search



This Category All Categories