Jump to content

[SOLVED] Creating an Array of Files in a Directory [[Recursive]]


Xeoncross

Recommended Posts

 

Well, I have been working on a function that will take several different parameters and recursively scan dir's and add their files to an array. This is so I can figure out what files are in each dir etc... However, my function WAS working and then all-of-a-sudden it stopped! I can't figure out what I did or changed that might have messed it up.

 

So can anyone run the code below and figure out what I am missing?

 

<?php

///////////////////////////////////////////////////////////
// A function to list all files within the specified directory 
// and it's sub-directories. This is a recursive function that 
// has no limit on the number of levels down you can search.
///////////////////////////////////////////////////////////
// What info does this function need?
/////////////////
//
// $data['start_dir']   The directory to start searching from                   (Required) ("./" = current dir, "../" = up one level)
// $data['good_ext']    The file extensions to allow.                           (Required) (set to 'array('all') to include everything)
// $data['skip_files']  An array of files to skip.                              (Required) (empty array if you don't want to skip anything)
// $data['recursive']   Keep digging deeper if you find more directories?       (required) (true or false)
// $data['limit']       The limit of dir to search                              (required)
//
/////////////////
// Example data
/////////////////
//
// $data['start_dir']      = "../../";
// $data['good_ext']       = array('php', 'html');
// $data['skip_files']     = array('..', '.', 'txt', '.htaccess');
// $data['recursive']      = true;
// $data['limit']          = 5;
//
//////////////////////////////////////////////////
function directory($data, $level=1) {

    //If the directory given actually IS a directory 
    if (is_dir($data['start_dir'])) {
    
        //Then open the directory 
        $handle = opendir($data['start_dir']);
        
        //while their are files in the directory...
        while (($file = readdir($handle)) !== false) {
        
            //If the file is NOT in the bad file list...
            if (!(array_search($file, $data['skip_files']) > -1)) {
            
                //Store the full file path in a var
                $path = $data['start_dir']. $file;
                
                //if it is a dir
                if (filetype($path) == "dir") {
                
                    //If the dir is NOT deeper than the limit && 'recursive' is set to true
                    if( ($data['limit'] >= $level) && $data['recursive']){
                        
                        //Run this function on on the directory to see what is in it (this is where the recursive part starts)
                        $files2 = directory(array('start_dir' => $path. '/', 'good_ext' => $data['good_ext'], 'skip_files' => $data['skip_files'], 'recursive' => $data['recursive'], 'limit' => $data['limit']), $level + 1);
                        
                        //then combine the output with the current $files array
                        if(is_array($files2)) { $files = array_merge($files, $files2); }
                        
                    }
                
                //Else if it is a file
                } else {
                
                    //get the extension of the file
                    $ext = explode(".", $file, 1);
                    
                    //And if it is in the GOOD file extension list OR if the list is set to allow ALL files
                    if( (array_search($ext[1], $data['good_ext']) > -1) || ($data['good_ext'][0] == "all") ) {
                    
                        //Add the file to our list
                        $files[$path]['level'] = $level;
                        $files[$path]['dir'] = end(explode('/', $data['start_dir']));
                        $files[$path]['file'] = $file;
                        $files[$path]['size'] = filesize($path);
                        $files[$path]['ext'] = $ext[1];
                        
                    }
                }
            }
        }
        
        //Close the dir handle
        closedir($handle);
        
        //Return the result (sorted by by KEYS)
        return ksort($files);
        
    } else {
        return array('not a valid directory');
    }
}

?>

 

You can run it by something like this:

 

<?php

$data['start_dir']      = "../../";                         //The directory to start searching from
$data['good_ext']       = array('php', 'class');         //The file extensions to allow (set to 'array('all') to include everything)
$data['skip_files']     = array('..', '.', '.htaccess');   //The files to skip set to an empty array if you don't want to skip anything.
$data['recursive']      = true;                         //Keep digging deeper if you find more director
$data['limit']          = 5;
    
$files = directory($data);
    
print_r($files);

?>

 

Thanks!  ;D

 

Link to comment
Share on other sites

 

bump  ;D

 

It is a really simple thing to dig through dirs - but adding features like recursion and creating array lists adds a extra level to the puzzle.

 

List all files in the current directory and strip out .  and ..

<?php
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "$file\n";
        }
    }
    closedir($handle);
}
?> 

 

Link to comment
Share on other sites

 

man, I was just being dumb - I found the problem. It would return a "1" sometimes and I couldn't figure out how an array could go from array() to "1".

Well duh:

 

<?php

//Return the result (sorted by by KEYS)
return ksort($files);

?>

 

ksort returns "1" (true) on successes or "0" (false) on failure.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.