Take the 2-minute tour ×

I have now the following code:

$files = scandir($imagepath);

But when i display the images i also get hidden files. I want to excluse those hidden files.

Thanks in advance.

share|improve this question
add comment

4 Answers

up vote 13 down vote accepted

The lazy solution would be:

 $files = preg_grep('/^([^.])/', scandir($imagepath));
share|improve this answer
Lazy = good. Also, works with PHP < 5.3 –  Mateng May 2 '13 at 16:50
While this solution may work for the "hidden" files in the example this does not in fact exclude hidden files that have standard file names eg. 'Thumbs.db' is a common file that will be hidden but still be found in the above search. –  elzaer Sep 19 '13 at 1:37
add comment

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();
share|improve this answer
Just to clarify, isDot() doesn't ignore files that starts with .. Just tried on my system PHP 5.3.5. –  resting Mar 11 '13 at 6:11
add comment

Assuming the hidden files start with a . you can do something like this when outputting:

foreach($files as $file) {
    if(strpos($file, '.') !== (int) 0) {
        echo $file;

Now you check for every item if there is no . as the first character, and if not it echos you like you would do.

share|improve this answer
add comment

I am still leaving the checkmark for seengee's solution and I would have posted a comment below for a slight correction to his solution.

His solution masks the directories(. and ..) but does not mask hidden files like .htaccess

A minor tweak solves the problem:

foreach(new DirectoryIterator($curDir) as $fileInfo) {
    //Check for something like .htaccess in addition to . and ..
    $fileName = $fileInfo->getFileName();
    if(strlen(strstr($fileName, '.', true)) < 1) continue;

     echo "<h3>" . $fileName . "</h3>";
share|improve this answer
add comment

Your Answer


