网络营销电子商务研究中心

网络营销电子商务研究中心 (https://www.0058.net/index.php)
-   PHP (https://www.0058.net/forumdisplay.php?f=75)
-   -   How to get only images using scandir in PHP? (https://www.0058.net/showthread.php?t=5830)

Kealia 2016-08-16 12:53 AM

How to get only images using scandir in PHP?
 
Is there any way to get only images with extensions jpeg, png, gif etc while using
Code:

$dir    = '/tmp';
$files1 = scandir($dir);


Kellerton 2016-08-16 12:54 AM

You can use glob
Code:

$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.

Kendall 2016-08-16 12:55 AM

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

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


Kennedyville 2016-08-16 12:56 AM

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.
Code:

// 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.


All times are GMT +8. The time now is 10:44 PM.

Powered by vBulletin Version 3.8.7
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.