Return to Snippet

Revision: 24874
at March 13, 2010 14:35 by Lostindream


Updated Code
/* Reading directory contents
  * @param STRING $dir - Name of the directory
  * @param STRING $filter - Regular expression
  * @param BOOLEAN $type - 0 => Files and directories, 1 => Only files, 2 => Only directories
  * @return ARRAY|BOOLEAN - Returning array if success, else FALSE */

 function dirContents($dir, $filter=null, $type=0)
 {
  $dir .= "/";
  $dir = eregi_replace("[\/]+","/", $dir);
  if(is_dir($dir) && $d=opendir($dir))
  {
   $files = array();

   while(($file=readdir($d)) !== false)
   {
    if($file!="." && $file!="..")
    {
     if($type==1 && is_dir($dir.$file)) {continue;}
     if($type==2 && !is_dir($dir.$file)) {continue;}
     if($filter!==null && !preg_match("/".$filter."/i",$file)) {continue;}
     $arrayOfFiles[] = $file;
    }
   }
   closedir($d);
   sort($arrayOfFiles,SORT_LOCALE_STRING);
   return($arrayOfFiles);

  }else{return false;}
 }

Revision: 24873
at March 13, 2010 14:24 by Lostindream


Initial Code
/* Reading directory contents
  * @param STRING $dir - Name of the directory
  * @param STRING $filter - Regular expression
  * @param BOOLEAN $type - 0 => Files and directories, 1 => Only files, 2 => Only directories
  * @return ARRAY|BOOLEAN - Returning array if success, else FALSE */

 function dirContents($dir, $filter=null, $type=0)
 {
  $dir .= "/";
  $dir = eregi_replace("[\/]+","/", $dir);
  if(is_dir($dir) && $d=opendir($dir))
  {
   $files = array();
   $i = 0;
   while(($file=readdir($d)) !== false)
   {
    if($file!="." && $file!="..")
    {
     if($type==1 && is_dir($dir.$file)) {continue;}
     if($type==2 && !is_dir($dir.$file)) {continue;}
     if($filter!==null && !preg_match("/".$filter."/i",$file)) {continue;}
     $arrayOfFiles[] = $file;
     $i++;
    }
   }
   closedir($d);
   sort($arrayOfFiles,SORT_LOCALE_STRING);
   return($arrayOfFiles);

  }else{return false;}
 }

Initial URL

                                

Initial Description
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.

Initial Title
Comfortable directory contents with filters

Initial Tags
php, file, regexp, filter, directory

Initial Language
PHP