Find a file (including subdirectory search)


/ Published in: PHP
Save to your folder(s)

This function searches the current working directory (or any other directory path that you specify with parameter $p) for a file, named $f, and returns the full path and filename of the first occurrence, or false if it is either not found or the maximum number of comparisons is reached. The return value is relative to the executing script, so you can safely pass this function to other file-handling functions, e.g. fopen(FFIND("my.file")); or file(FFIND("my.file"));


Copy this code and paste it in your HTML
  1. function FFIND($f,$p=null,$l=1000)
  2. { // Recursively find a file $f in directory $p (compare up to $l files)
  3. // Returns the full path of the first occurrence (relative to current directory)
  4. // (c) Peter Mugane Kionga-Kamau http://www.visionhive.com
  5. // Free for unrestricted use with this notice and description unaltered.
  6. $cd=$p==null?getcwd():$p;
  7. if(substr($cd,-1,1)!="/")$cd.="/";
  8. if(is_dir($cd))
  9. {
  10. $dh=opendir($cd);
  11. while($fn=readdir($dh))
  12. { // traverse directories and compare files:
  13. if(is_file($cd.$fn)&&$fn==$f){closedir($dh);return $cd.$fn;}
  14. if($fn!="."&&$fn!=".."&&is_dir($cd.$fn)){$m=ffind($f,$cd.$fn,$l);if($m){closedir($dh);return $m;}}
  15. }
  16. closedir($dh);
  17. }
  18. return false;
  19. }

URL: http://www.visionhive.com

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.