How to get only images using scandir in PHP?

后端 未结 6 1319
逝去的感伤
逝去的感伤 2020-11-27 15:52

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

$dir    = \'/tmp\';
$files1 = scand         


        
6条回答
  •  一整个雨季
    2020-11-27 16:08

    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.

提交回复
热议问题