Comfortable directory contents with filters


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

Very simple to use.

**Calling:**

$files = dirContents(DIR_PATH, [FILTER, [TYPE]]);

**Examples:**

$files = dirContens("my-dir");
_$files_ is array containing all, both files either directories

$files = dirContens("my-dir", "img[0-9]");
_$files_ is array containing files or directories with 'img0', 'img1', 'img2', etc. in their names

$files = dirContents("my-dir/", "\.php", 1);
_$files_ is array containing only files with '.php' in their names

**Tip:**
After calling _dirContents()_ try to call *print_r* for showing the array of files

echo '<pre>';
print_r($files);
echo '</pre>';

Thank you for your comments.


Copy this code and paste it in your HTML
  1. /* Reading directory contents
  2.   * @param STRING $dir - Name of the directory
  3.   * @param STRING $filter - Regular expression
  4.   * @param BOOLEAN $type - 0 => Files and directories, 1 => Only files, 2 => Only directories
  5.   * @return ARRAY|BOOLEAN - Returning array if success, else FALSE */
  6.  
  7. function dirContents($dir, $filter=null, $type=0)
  8. {
  9. $dir .= "/";
  10. $dir = eregi_replace("[\/]+","/", $dir);
  11. if(is_dir($dir) && $d=opendir($dir))
  12. {
  13. $files = array();
  14.  
  15. while(($file=readdir($d)) !== false)
  16. {
  17. if($file!="." && $file!="..")
  18. {
  19. if($type==1 && is_dir($dir.$file)) {continue;}
  20. if($type==2 && !is_dir($dir.$file)) {continue;}
  21. if($filter!==null && !preg_match("/".$filter."/i",$file)) {continue;}
  22. $arrayOfFiles[] = $file;
  23. }
  24. }
  25. closedir($d);
  26. sort($arrayOfFiles,SORT_LOCALE_STRING);
  27. return($arrayOfFiles);
  28.  
  29. }else{return false;}
  30. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.