Tuesday, March 6, 2018

looked up php read directory 100 times...

I guess this is my favorite way of getting the contents of a directory / folder in PHP,
$files = array_values(array_diff(scandir($path), array('.', '..')));
from StackOverflow (surprise, surprise)

UPDATE APRIL 2019: I added the array_values() call to it, since otherwise the array seems to "start" at 2, and is a map instead of array if you pass it to json_encode()

And just because I've written this at least once in Perl and PHP and might use it again - a clunky function (clunky and clear is good, I think, or at least better than elegant and tough to read when I don't do ALL that much PHP) to read a directory - AFTER verifying it's under a certain directory root with realpath, ala...

$ROOT = "/some/legal/root/";
$folder = realpath($_REQUEST["folder"]);
if(substr($folder,0,strlen($ROOT)) != $ROOT ){
    $folder = $ROOT;


I have a function like this, that I call twice, once for dirs once for plain files, plus it adds a css class if the file is a hidden "dot" file... and yeah I'm assuming "/" as the path separator, sosueme...

function printFiles($folder,$doDirs) {
    if(!(substr(strrev($folder),0,1) == "/")){
        $folder .= "/";

    }
    $files = array_diff(scandir($folder), array('.', '..'));
    asort($files);
    foreach($files as $i => $filename){
        $path = $folder.$filename;
        if(($doDirs && is_dir($path)) || ((!$doDirs) && (! is_dir($path)))){
            $slash = $doDirs?"/":"";
            $typeclass = $doDirs?"dir":"file";
            $hiddenclass = (substr($filename,0,1) == ".")?"hidden":"";
            print "<a href='$path' class='$typeclass $hiddenclass'>$filename$slash</a> ";
        }
    }
}

No comments:

Post a Comment