PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Everah | Please do not edit the title to show number of pages.
right now i have a working php script that shows all the files in the directory and puts a link on it, but what i want is to not only have the file names, but after the file names (in a different form) have the file type, and then after that have the file size. and eventually i wana be able to click on "file size" and have it sort by file size. is that possible?
while you are looping through the directory, instead of echoing out the name, store the filename, size, and whatever other information into an array and then sort that array with sort, or usort, or whatever... and then loop through THAT array and output the file info.
<?php
$directory = "./filebin";
// Function to sort files by size
function sort_by_size($a, $b){
// Compare the two files to see which is larger (you may refer to the usort() documentation to understand how this works)
if ($a['size'] == $b['size']) {
return 0;
}
return ($a['size'] < $b['size']) ? -1 : 1;
}
$dir = dir($directory);
$files = array();
while (($filename = $dir->read()) !== false) {
$file_info = array();
if(is_file($dir->path . "/" . $filename)){
// Gather file info and store it into an array
$file_info['name'] = $filename;
$file_info['path'] = realpath($dir->path . "/" . $filename);
$file_info['size'] = filesize($file_info['path']);
$files[] = $file_info;
}
}
// Sort the array using the function above
usort($files, 'sort_by_size');
// This is just to show that it has been sorted
print_r($files);
?>
I wrote a little method that takes an array of file extension and allows for them to be read and listed for display/linking. You can use this as a guide as well (though Ninja's looks to be a little more suited to what you are doing).
everah, i dunno what the F**K u just did, but it's way too complicated. lol. so i'm stickin wit ninja's code.
BUT, ninja, question: Array ( [0] => Array ( [name] => trial1.doc [path] => /filebin/trial1.doc [size] => 8258 ) )
is what comes up...so like yea. how do i make it less "code-ey" i guess lol.
no... my guess is that you passed it an invalid directory... this is probably a given, but did you change the $directory variable to the directory you need it to iterate? also... check whether the directory is a directory before doing any of that code with is_dir(). I forgot to add that check in there.
EDIT: I wrote the above before you edited your post. To answer your new question... now just do what you did in the first place, iterate through the array (instead of print_r) and echo out the filenames.