Page 1 of 1

How to iterate files inside a folder using PHP

Posted: Mon Dec 14, 2009 8:02 pm
by Neo
The following code will iterate all files in a folder.

Code: Select all

$dir = '/path/to/files'; 
if ($handle = opendir($dir)) { 
 while(false!== ($file = readdir($handle))) { 
   if ($file == '.' && $file == '..') continue; 

   // your code here

 } 
 closedir($handle);  
}
 
To skip certain file types use following code in place of "your code here" (file mode of rest of the files will be changed to '777' in this example).

Code: Select all

   if ( !is_file($dir.$file) ){
      if (preg_match("'\.(html¦jpe?g¦gif)$'", $file) ){
            continue;
      }
      else{
            chmod($dir.$file, 0777); 
      } 
   }