Hi everyone,
I’m using opendir() and then readdir() to get the contents of a folder (be it files or sub-folders).
The strange thing about the code below is that it works but the array it passes back only ever contains 5 elements (i.e. five files). Normally one would think it must not be iterating through all the files/folders thus not filling the array up but $count below echo’s out from 0 up to 364, which just so happens to be correct since there’s 365 elements in total in the searched folder.
I know this for a fact since I do the below:
$result = getDirectoryList($dir);
for ($i = 0; $i <= sizeof($result); $i++) {
echo "<br>" .$result['$name '][$i]."<br>";
}
…and sizeof($result) is always 4 (5 elements -> id’s 0-4).
My questions are:
a) Where is it going wrong?
b) Given that mime_content_type() is now an oldie how to successfully get the file mime type via finfo() so it yields a string such as “text/css”?
Code follows:
class Directory_Data
{
public $name;
public $type;
public $size;
public $lastmod;
}
function getDirectoryList($dir)
{
//holds all directory data
$directory_data[] = new Directory_Data();
//set directory contents counter
$count = 0;
//add trailing slash if missing
if(substr($dir, -1) != "/") $dir .= "/";
//open pointer to directory and read list of files
$directory_handle = opendir($dir) or die("Opps: Failed opening directory $dir for reading");
//while the directory contains files or sub-directories
while (($file = readdir($directory_handle)) !== false) {
if (($file <> ".") && ($file <> "..")) {
//if we have stumbled across a sub-directory
if(is_dir("$dir$file")) {
echo "Count (Folder): " .$count ."<br>";
$directory_data['$name '][$count] = "$dir$file/";
//$directory_data['$type '][$count] = filetype("$dir$file");
$directory_data['$size '][$count] = 0;
$directory_data['$lastmod '][$count] = filemtime("$dir$file");
}
//if we have stumbled across a file
elseif (is_readable("$dir$file")) {
echo "Count (File): " .$count ."<br>";
$directory_data['$name '][$count] ="$dir$file";
//$directory_data['$type '][$count] = filetype("$dir$file");
$directory_data['$size '][$count] = filesize("$dir$file");
$directory_data['$lastmod '][$count] = filemtime("$dir$file");
}
$count++;
}
}
//close the directory pointer
closedir($directory_handle);
return $directory_data;
}
P.S. Yes directory listing is denied in my .htaccess but then I wouldn’t be able to read any files or folders. It will display the file/folder names if I echo them out within the readdir() loop, just not outside once the function quits and passes back an array. There’s also no PHP errors to signal a security access denied status.
Thank you,