I have wrote a function for getting all the subfolders of a folder. It also has the option of going the an upper level and displaying the folders....much like a file manager but it works only for folders and has a restriction to not go upper than the base folder so to prevent users from browsing the entire hard disk.
I am returning the result as a json object to be put in a div. My problem is this: On my windows box (using wamp) the folder "Up one Level" is always displayed on top of the folder list. When I upload it on my website it doesn't display on top but somewhere in the middle. I have wrote a function ( fixArray($array) ) to correct this...but it doesn't seem to work. The entire solution for this feature is provided so please help to make it work and for others to benefit from it. Just to mention: there is nothing wrong in the JS code. JSON object is parsed in the order it is sent by the php file.
function fixPath($path) {
$path = str_replace('/../', '/', $path);
$path = str_replace('/./', '/', $path);
return $path;
}
function fixArray($array) {
for($i = 0; $i < count($array); $i++) {
if(!strcmp($array[$i]['name'],"Up one Level")) {
$aux = $array[$i];
$array[$i] = $array[0];
$array[0] = $array[$i];
break;
}
}
}
function directoryList($basepath, $path) {
$dirStruct = array();
if(is_dir($path)) {
$handle = opendir($path);
while(($file = readdir($handle)) !== false) {
if($file != '.') {
if(@opendir($path.$file)) {
$newpath = "";
if($file == '..') {//begin constructing the path for the upper level
$array = @split('/',$path);
$up = "";
for($i = 0; $i < count($array) - 2; $i++) {
$up = $up.$array[$i].'/';
}
$file = "Up one Level";
//if the upper level exceeds the home dir
if(strcmp($up,$basepath) < 0) {
$newpath = $basepath;//use the basepath
}
else {
$newpath = $up;
}
}
else {//construct the path for a normal dir
$newpath = $path.$file.'/';
$newpath = fixPath($newpath);
}
$dirStruct[] = array('path' => $newpath, 'name'=>$file);
}
}
}
}
//sortArray($dirStruct);
fixpath($dirStruct);
return $dirStruct;
}