Return a list of files from a chosen directory

Date: 25th October 2007 at 11:01 pm | Filed under: development, scripts | Author: Sam Burdge

I found this really useful php script the other day. It returns a list of files from a given directory:

Read on…

3 Responses to “Return a list of files from a chosen directory”

  • Comment by c-received
    Date: November 6th, 2007 at 10:56 pm

    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();

  • Comment by Sam Burdge
    Date: November 14th, 2007 at 5:48 pm

    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);

  • Comment by c-received
    Date: November 16th, 2007 at 6:04 pm

    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.

Leave a Comment