07 June 2010 ~ 1 Comment

Listing files in a directory Codeigniter

The Directory Helper file contains functions that assist in working with directories.

First if you plan on using this often you may want to place this in your autoload under the config folder. Below is how you would load it in the controller itself.

$this->load->helper('directory');

Now you have access to the directory_map function, this function reads the directory path specified in the first parameter and builds an array representation of it and all its contained files.

$map = directory_map('/myfiles/');

Note: Paths are almost always relative to your main index.php file.


Sub-folders contained within the directory will be mapped as well. If you wish to map only the top level directory set the second parameter to true (boolean):

$map = directory_map('/myfiles/', TRUE);

By default, hidden files will not be included in the returned array. To override this behavior, you may set a third parameter to true (boolean):

$map = directory_map('/myfiles/', FALSE, TRUE);

Each folder name will be an array index, while its contained files will be numerically indexed. Here is an example of a typical array:

Array
(
   [libraries] => Array
   (
       [0] => benchmark.html
       [1] => config.html
       [database] => Array
       (
             [0] => active_record.html
             [1] => binds.html
             [2] => configuration.html
             [3] => connecting.html
             [4] => examples.html
             [5] => fields.html
             [6] => index.html
             [7] => queries.html
        )
       [2] => email.html
       [3] => file_uploading.html
       [4] => image_lib.html
       [5] => input.html
       [6] => language.html
       [7] => loader.html
       [8] => pagination.html
       [9] => uri.html
)

Codeigniter is a great framework, i use it in most all my projects. The easiest way I found to get started with Codeigniter is to use a book like CodeIgniter 1.7
from Amazon.

Tags: ,

One Response to “Listing files in a directory Codeigniter”

  1. Bud 9 June 2010 at 2:46 pm Permalink

    Very cool. Thanks for the help, it worked for me.