find the contents of a directory in php

To find the contents of a directory in PHP, you can use the scandir() or readdir() function.

Here is an example using scandir():

main.php
$dir = './my_directory';

// get the contents of the directory
$contents = scandir($dir);

// loop through each item in the directory
foreach ($contents as $item) {
    // ignore . and ..
    if ($item == '.' || $item == '..') {
        continue;
    }
    // output the item's name
    echo $item . '<br>';
}
310 chars
15 lines

And here is an example using readdir():

main.php
$dir = './my_directory';

// open the directory
if ($handle = opendir($dir)) {

    // loop through each item in the directory
    while (false !== ($item = readdir($handle))) {
        // ignore . and ..
        if ($item == '.' || $item == '..') {
            continue;
        }
        // output the item's name
        echo $item . '<br>';
    }

    // close the directory handle
    closedir($handle);
}
411 chars
19 lines

Both of these functions will return an array with the names of the files and directories in the specified directory. The . and .. entries are included, so you will need to skip over those if you don't want to include them in your output.

gistlibby LogSnag