How to iterate files inside a folder using PHP

Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

How to iterate files inside a folder using PHP

Post by Neo » Mon Dec 14, 2009 8:02 pm

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); 
      } 
   }
 
Post Reply

Return to “PHP & MySQL”