PHP List Directory

Here I will show you the correct way to read a folder in PHP. There are a few ways to list a folder in PHP but the function below seems to work the best for me. I will be using the PHP functions opendir(), readdir() and closedir() to complete the example.

One thing to remember is that the function readdir() returns FALSE if it fails, but it may also return another value that could be incorrectly evaluated as FALSE, such as zero or an empty string. For this reason, we use the exactly not equal to (!==) rather than just not equal to (!=).


// the directory we want to list in PHP
$folder = "/some/folder/to/read";

// attempt to open the folder and store the handle to the folder
if( $handle = opendir( $folder ) )
	echo "<h3>Reading Folder: $folder</h3>";

	// loop through each entry in the folder (shows files and sub directories)
	// Note: we use !== rather than !==
	while ( FALSE !== ( $entry = readdir( $handle ) ) )
		// list directory contents
        	echo "$entry<br />";

	// close the handle to the directory listed
	closedir( $handle );


Simple as that. That is all you will need to read a folder in PHP.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>