PHP Tip using opendir() and readdir()

Sometimes you may require a list of all of the files in a directory. Such a list can be built using the opendir() and readdir() functions:

<?php
$targetdir = “/var/tmp”;
$files = array();
$directory = opendir($targetdir);
while($filename = readdir($directory)){
#ignore . and ..
if(strlen($filename) > 2){
array_push($files, $filename);
}
}
?>

Upon execution, $files will be an array of filenames (basename only, with no path). If your directory contains files whose names are one or two characters long, you’ll need to replace the strlen() test with a comparison against the literals ‘.’ and ‘..’ in order to avoid adding the current and parent directory names to the array.

Comments are closed.