Tuesday, July 23, 2013

DirectoryIterator in PHP

The DirectoryIterator is an Iterator class which comes with PHP5 and it provides another way for viewing contents of any directory. It follows the object-oriented approach. Let's check out one example..

<?php
// Create DirectoryIterator Object with path as parameter
$folder = new DirectoryIterator("joomla2.5.9");

// Browse Folder
foreach( $folder as $f )
 echo ( $f->getFilename() . "<br>");
?>


The above code displays all sub-folders (including '.' and '..') and files under the path provided as argument while calling the DirectoryIterator constructor. We can identify if an entry is a file or folder using various methods of the class. Check the example below.

<?php
// Create DirectoryIterator Object with path as parameter
$folder = new DirectoryIterator("joomla2.5.9");

// Browse Folder
foreach( $folder as $f )
{
   // If special '.' or '..' folder, ignore
   if( !$f->isDot() )
   {
     // Directory
     if( $f->isDir() )
     {
       echo ( $f->getFilename() . " [Directory] <br>");
     }
     else // File
     {
       // Permission returns an integer, convert it to Octal
       $octal_perms = substr(sprintf('%o', $f->getPerms()), -4);
       // Print File Details
       echo "FileName : {$f->getBasename()}, Extension : [{$f->getExtension()}], ";
       echo "FileSize : {$f->getSize()} Bytes, Permissions : [$octal_perms] ";
       echo "Last Modified : ".date('Y-m-d',$f->getMTime())."<br>";
     }
   }
}
?>


The above code is pretty self-explaining. Now, let is recursively use the above method to fetch all the sub-folder contents.

<?php
// Create DirectoryIterator Object with path as parameter
$folder = "joomla2.5.9";

// Call the function
get_folder_contents( $folder );

/// FUnction Definition
function get_folder_contents( $folder )
{
  // Create Iterator Object
  $folder_name = new DirectoryIterator($folder);

  // Browse Folder
  foreach( $folder_name as $f )
  {
       // If special '.' or '..' folder, ignore
       if( !$f->isDot() )
       {
         // Directory
         if( $f->isDir() )
         {
           // Print Directory Name
           echo (" ---- Showing Contents of $folder/{$f->getFilename()} ---- <br>");
          
           // RECURSIVE CALL
           get_folder_contents( $folder . "/" . $f->getFilename() );
         }
         else // File
         {
           // Permission returns an integer, convert it to Octal
           $octal_perms = substr(sprintf('%o', $f->getPerms()), -4);
           // Print File Details
           echo "FileName : {$f->getBasename()}, Extension : [{$f->getExtension()}], <br>";
         }
       }
  }
}
?>


The DirectoryIterator class also provides some methods like current(), next(), rewind() which moves Iterator cursor. Check one example below..

<?php
// Get the Current directory
$folder = new DirectoryIterator( dirname(__FILE__) );

// Check if the pointer position is a valid entry
// We are browsing for FILES first
while($folder->valid())
{
    // GET the Current file/folder
    // iteator pointer is pointing to.
    $file = $folder->current();
   
    // Check if it is a FILE
    if( !$file->isDir() )
    {
       // Echo Key :: FileName
       echo $folder->key() . " :: " . $file->getFilename() . "<br>";
    }
   
    // Move the pointer pointing to next item
    $folder->next();
}

// Let's search for Directories
// Hence move the pointer to the beginning
$folder->rewind();

// Again start the loop
while($folder->valid() )
{
  // GET the Current file/folder
  $dir = $folder->current();
 
  // Check if it is a Directory
  if( $dir->isDir() )
      echo $folder->key() . " :: " . $dir->getFilename() . "<br>";

  // Move the pointer to the next item
  $folder->next();   
}
?>


We have used rewind() function to move the iterator pointer pointing to the beginning of the file/folder listing. The next() function moves the pointer to the next item in the list. The key() function returns a key value (integer) which I think the sorted index for each item.

Check previous articles on file/folder browsing in PHP : File and folder Iterators in PHP, Using Glob in PHP

No comments: