Get Files From Folder

April 28th, 2008 | by admin | |

Need to get a list of files from a folder on your server? Maybe it’s a list of photos that you want to manipulate with PHP, this function will grab all files from a specified directory and return them in an array for you. It uses recursive logic, calling itself to drop down all folders and subfolders.

<?php
//recursive function to create an array of files from a physical directory
function get_files($directory_to_scan) {
    //Try to open the directory
    if($dir = opendir($directory_to_scan)) {
        //Create an array for all files found
        $tmp = Array();
        //Add the files
        while($file = readdir($dir)) {
            //Make sure the file exists
            if($file != "." && $file != ".." && $file[0] != '.') {
                //If it's a directiry, list all files within it
                if(is_dir($directory_to_scan . "/" . $file)) {
                    $tmp2 = get_files($directory_to_scan . "/" . $file, "/" . $file);
                    if(is_array($tmp2)) {
                        $tmp = array_merge($tmp, $tmp2);
                    }
                } else {
                    array_push($tmp, "/" . $file);
                }
            }
        }
        //Finish off the function
        closedir($dir);
        return $tmp;
    }
}
?>

Post a Comment