How to get a simple File Listing in PHP Programming 08 AUG 2013

green php elephants - elephpantsReturning a list of files contained in a folder in PHP is turned into something fairly trivial, thanks to the built in readdir function. Basically, the function returns the name of the next entry from the currently open directory handle resource, itself opened with the standard opendir command.

(Note, if the directory handle is not specified, the last link opened by opendir() is assumed.)

The readdir function returns the file name entries in the order in which they are stored by the filesystem, meaning that it is up to you if you want to present them ordered in a particular fashion.

So in practice, a simple file listing in PHP would look as follows:

if ($handle = opendir($_SERVER['DOCUMENT_ROOT'] . '/portal/widget_scripts')) {
    echo "Directory handle: $handle\n";
    echo "Entries:\n";
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "<p>$entry</p>\n";


Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.