Get filenames of images in a directory

Hammad Khalid picture Hammad Khalid · Dec 7, 2011 · Viewed 18.3k times · Source

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.

Answer

Leonard picture Leonard · Dec 7, 2011

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