08 December, 2010

Get all files inside a directory using php

Listing of files inside a directory can be done simply using php.
Following function can be used to list all the files inside a directory.

function list_directory($dirpath) {
$files = array(); //files array
$dirs = array(); //directories array
$file_num = 0; //set number of files to 0
$dir_num = 0; //set number of directories to 0
//check if the path is a directory
if (is_dir($dirpath)) {
//create a handle for opening directory
$hndl = opendir($dirpath);
//start the loop
do {
//read the directory
$fle = readdir($hndl);
if ($fle !== FALSE && $fle != "." && $fle != "..") {
//check if its a directory or a file
if (is_dir("$dirpath/$fle")) $dirs[$dir_num++] = $fle;
else $files[$file_num++] = $fle;
}
} while($fle !== FALSE);
closedir($hndl);
}
return array($dir_num, $file_num, $dirs, $files);
}

No comments: