Return a list of files from a chosen directory
I found this really useful php script the other day. It returns a list of files from a given directory:
I found this really useful php script the other day. It returns a list of files from a given directory:
Site powered by WordPress | 76 digital remix by Sam Burdge | © 2009 Sam Burdge
A rough and ready PHP Class for displaying directories and files separately. I’ve added a bit of error checking hence the @ symbol and die instruction. Let us know what you think?
class ListDir {
function __construct($dir=null){
$this->directory=array();
$this->file=array();
if(isset($dir)){
$dh = @opendir($dir) or die(”Go make a cup of tea: opendir($dir)”);
while(($item = @readdir($dh))!==false){
if($item==’.'||$item==’..’||$item==’Thumbs.db’){continue;}
if(is_file($dir.’/’.$item))array_push($this->file,$item);
if(is_dir($dir.’/’.$item))array_push($this->directory,$item);
}
closedir($dh);
}
return true;
}
public function showFiles(){
var_dump($this->file);
}
public function showDirectories(){
var_dump($this->directory);
}
}
$directories = new ListDir(’/home/system/www/’);
$directories->showDirectories();
$files = new ListDir(’/home/system/www/’);
$files->showFiles();
This method is simplistic. It also recognises whether it’s a file or folder, and changes the directory path acordingly.
if($path==”){
$path = “files”;}
$dh = opendir($path);
$i=1;
while (($file = readdir($dh)) !== false) {
if($file != “.” && $file != “..”) {
$findme = ‘.’;
$pos = strpos($file, $findme);
if($pos == false){
echo “$i. <a href=’?path=$path/$file’ rel=”nofollow”>$file (Folder)</a><br />”;} else {echo “$i. <a href=’$path/$file’ rel=”nofollow”>$file</a><br />”;}
$i++;
}
}
closedir($dh);
Hey Sam,
In the code above you could take on a more OO approach. This could mean applying default properties within the object, under a bespoke name space for clarity. Also by boot strapping the object with some custom methods, assessors or mutators can help with extracting, adding or modifying properties within the object.
A lot of the time you also want to improve the programmes performance, both in terms of the server load and maintainability, and make the application as extensionable as possible, e.g. being able to create, extend and mutate any properties at will.
Also its good to maintain some separation between the business logic and the ui side of things.