How to get only images using scandir in PHP?

♀尐吖头ヾ 提交于 2019-11-26 20:16:40

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.

Rajesh Kumar R

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.

Josiah

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;
}

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.

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

scandir does not have the functionality you seek.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!