PHP list dir

09.Jul.2010

Many times I have written functions for reading directory list. It was quite a horrible code until I found glob() – a PHP list dir function. So, in order to make life easier, here’s a snippet that shows you how to use this PHP list dir function:

1
2
3
4
5
6
$dir = $_SERVER['DOCUMENT_ROOT'] . '/some-dir/gallery/*';
 
// glob() opens dir as array of files, so we just print its content
foreach(glob($dir) as $file)  {
	echo "Filename: $file : filetype: " . filetype($file) . "<br />";
}

Since this PHP list dir function uses pattern for finding files, we can now easily search through list of specific file type.

More examples:

Listing through JPEG images:

1
2
3
4
5
$dir = $_SERVER['DOCUMENT_ROOT'] . '/some-dir/gallery/*.jpg';
 
foreach(glob($dir) as $file)  {
	echo "Filename: $file : filetype: " . filetype($file) . "<br />";
}

Listing through different file types:

1
2
3
4
5
$dir = $_SERVER['DOCUMENT_ROOT'] . '/some-dir/gallery/';
 
foreach(glob($dir . '{*.jpg,*.gif}', GLOB_BRACE) as $file)  {
	echo "Filename: $file : filetype: " . filetype($file) . "<br />";
}