Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude hidden files from scandir

I am using the following code to get a list of images in a directory:

$files = scandir($imagepath);

but $files also includes hidden files. How can I exclude them?

like image 987
Sino Avatar asked Dec 16 '11 10:12

Sino


3 Answers

On Unix, you can use preg_grep to filter out filenames that start with a dot:

$files = preg_grep('/^([^.])/', scandir($imagepath));
like image 72
mario Avatar answered Oct 15 '22 17:10

mario


I tend to use DirectoryIterator for things like this which provides a simple method for ignoring dot files:

$path = '/your/path';
foreach (new DirectoryIterator($path) as $fileInfo) {
    if($fileInfo->isDot()) continue;
    $file =  $path.$fileInfo->getFilename();
}
like image 6
robjmills Avatar answered Oct 15 '22 16:10

robjmills


$files = array_diff(scandir($imagepath), array('..', '.'));

or

$files = array_slice(scandir($imagepath), 2);

might be faster than

$files = preg_grep('/^([^.])/', scandir($imagepath));
like image 5
Agnel Vishal Avatar answered Oct 15 '22 16:10

Agnel Vishal