How to get only images using scandir in PHP?
Asked Answered
A

7

51

Is there any way to get only images with extensions jpeg, png, gif etc while using

$dir    = '/tmp';
$files1 = scandir($dir);
Alkahest answered 12/7, 2010 at 7:19 Comment(0)
A
98

You can use glob

$images = glob('/tmp/*.{jpeg,gif,png}', GLOB_BRACE);

If you need this to be case-insensitive, you could use a DirectoryIterator in combination with a RegexIterator or pass the result of scandir to array_map and use a callback that filters any unwanted extensions. Whether you use strpos, fnmatch or pathinfo to get the extension is up to you.

Anandrous answered 12/7, 2010 at 7:20 Comment(4)
That... doesn't use scandir() anymore. But is otherwise correct. So shouldn't that be "no, with glob"?Dorinda
Now make it case insensitive. >:)Wrenn
@Wrenn evil hearted you!! :PAnandrous
But it doesn't support unicode-charator filename. :(Norword
B
71

The actual question was using scandir and the answers end up in glob. There is a huge difference in both where blob considerably heavy. The same filtering can be done with scandir using the following code:

$images = preg_grep('~\.(jpeg|jpg|png)$~', scandir($dir_f));

I hope this would help somebody.

Biotechnology answered 6/7, 2016 at 13:15 Comment(1)
This works well, but RegEx should have an 'i' after the ending tilde to make it case-INSensitive, so as to not filter out image / graphic filenames with uppercase extensions like .PNG or .JPGAltorilievo
W
14

I would loop through the files and look at their extensions:

$dir = '/tmp';
$dh  = opendir($dir);
while (false !== ($fileName = readdir($dh))) {
    $ext = substr($fileName, strrpos($fileName, '.') + 1);
    if(in_array($ext, array("jpg","jpeg","png","gif")))
        $files1[] = $fileName;
}
closedir($dh);
Weatherproof answered 12/7, 2010 at 7:24 Comment(0)
I
14

Here is a simple way to get only images. Works with PHP >= 5.2 version. The collection of extensions are in lowercase, so making the file extension in loop to lowercase make it case insensitive.

// image extensions
$extensions = array('jpg', 'jpeg', 'png', 'gif', 'bmp');

// init result
$result = array();

// directory to scan
$directory = new DirectoryIterator('/dir/to/scan/');

// iterate
foreach ($directory as $fileinfo) {
    // must be a file
    if ($fileinfo->isFile()) {
        // file extension
        $extension = strtolower(pathinfo($fileinfo->getFilename(), PATHINFO_EXTENSION));
        // check if extension match
        if (in_array($extension, $extensions)) {
            // add to result
            $result[] = $fileinfo->getFilename();
        }
    }
}
// print result
print_r($result);

I hope this is useful if you want case insensitive and image only extensions.

Isborne answered 29/4, 2015 at 15:39 Comment(0)
D
9

You can search the resulting array afterward and discard files not matching your criteria.

scandir does not have the functionality you seek.

Dorinda answered 12/7, 2010 at 7:20 Comment(0)
M
3

If you would like to scan a directory and return filenames only you can use this:

$fileNames = array_map(
    function($filePath) {
        return basename($filePath);
    },
    glob('./includes/*.{php}', GLOB_BRACE)
);

scandir() will return . and .. as well as the files, so the above code is cleaner if you just need filenames or you would like to do other things with the actual filepaths

Microscopy answered 18/11, 2017 at 17:17 Comment(0)
T
1

I wrote code reusing and putting together parts of the solutions above, in order to make it easier to understand and use:

<?php
//put the absolute or relative path to your target directory
$images = scandir("./images");
$output = array();
$filer = '/(.jpg|.png|.jpeg|.gif|.bmp))/';
foreach($images as $image){
  if(preg_match($filter, strtolower($image))){
    $output[] = $image;
  }
}
var_dump($output);
Ternion answered 18/9, 2021 at 21:39 Comment(2)
This doesn't work: Compilation failed: unmatched closing parenthesisShaylyn
There is one extra parenthesis in the $filter on line 5. Also it's misspelled as $filer. Otherwise seems to work fine!Greenes

© 2022 - 2024 — McMap. All rights reserved.