Get filenames of images in a directory

寵の児 提交于 2019-11-27 06:08:43

问题


What should be done to get titles (eg abc.jpg) of images from a folder/directory using PHP and storing them in an array.

For example:

a[0] = 'ac.jpg'
a[1] = 'zxy.gif'

etc.

I will be using the array in a slide show.


回答1:


It's certainly possible. Have a look at the documentation for opendir and push every file to a result array. If you're using PHP5, have a look at DirectoryIterator. It is a much smoother and cleaner way to traverse the contents of a directory!

EDIT: Building on opendir:

$dir = "/etc/php5/";

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        $images = array();

        while (($file = readdir($dh)) !== false) {
            if (!is_dir($dir.$file)) {
                $images[] = $file;
            }
        }

        closedir($dh);

        print_r($images);
    }
}



回答2:


'scandir' does this:

$images = scandir($dir);



回答3:


One liner :-

$arr = glob("*.{jpg,gif,png,bmp}", GLOB_BRACE) 



回答4:


glob in php - Find pathnames matching a pattern

<?php
    //path to directory to scan
    $directory = "../images/team/harry/";
    //get all image files with a .jpg extension. This way you can add extension parser
    $images = glob($directory . "{*.jpg,*.gif}", GLOB_BRACE);
    $listImages=array();
    foreach($images as $image){
        $listImages=$image;
    }
?>


来源:https://stackoverflow.com/questions/8414746/get-filenames-of-images-in-a-directory

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