PHP Directory Listing

PHP code to list a directory. A nice textarea box for you to cut and paste is at the bottom of the page.



// open this directory
$myDirectory = opendir(".");

if(!empty($myDirectory)){
        // get each entry
        while($entryName = readdir($myDirectory)) {
                if (
                                $entryName != "." && $entryName != ".."
                                && $entryName != "index.php"
                                && !(is_dir($entryName))
                                && (preg_match("/\.php$|\.htm$|\.html$|\.pdf$|\.zip$/",$entryName))
                   ){
                        $dirArray[] = $entryName;
                }
        }

        // close directory
        closedir($myDirectory);

        if (is_array($dirArray)){
                //      count elements in array
                $indexCount     = count($dirArray);
                Print ("<p>$indexCount files:</p>\n");
                // sort 'em
                sort($dirArray);
                // print 'em
                print("<TABLE border=1>\n");
                print("<TR>
                        <TH>Filename</TH>
                        <th>Filetype</th>
                        <th>Date</th>
                        <th>Filesize</th>
                        </TR>\n");

                for($index=0; $index< $indexCount; $index++) {
                        if (substr("$dirArray[$index]", 0, 1) != "."){
                                print("<TR><TD><a href=\"$dirArray[$index]\">$dirArray[$index]</a></td>");
                                print("<td>");
                                print(filetype($dirArray[$index]));
                                print("</td>");
                                print("<td>");
                                print(date ("F d Y H:i:s",filemtime($dirArray[$index])));
                                print("</td>");
                                print("<td>");
                                print(number_format(filesize($dirArray[$index])));
                                print("</td>");
                                print("</TR>\n");
                        }
                }
                print("</TABLE>\n");

        }else{
                print ("<p>Nothing here</p>\n");
        }
}else{
        print ("<p>Sorry, couldn't read directory.</p>\n");
}

Cut and paste the code from here:

Online Sales | Tools | Contact