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:
function dirList ($directory) { // create an array to hold directory list $results = array(); // create a handler for the directory $handler = opendir($directory); // keep going until all files in directory have been read while ($file = readdir($handler)) { // if $file isn't this directory or its parent, // add it to the results array if ($file != '.' && $file != '..') $results[] = $file; } // tidy up: close the handler closedir($handler); // create a link to each file foreach($results as $key => $value){ echo '<a href="files/' . $value . '">' . $value . '</a>';} } echo ' <h2>Files</h2> '; //output the links dirList('files');






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.