Get filenames of images in a directory
Asked Answered
S

4

8

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.

Sontag answered 7/12, 2011 at 11:43 Comment(0)
B
13

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);
    }
}
Bailment answered 7/12, 2011 at 11:47 Comment(0)
T
5

'scandir' does this:

$images = scandir($dir);
Thrasonical answered 7/12, 2011 at 11:50 Comment(3)
scandir is safest than glob because directory can contain regex charsMyopic
Why is this not the accepted answer?! Beautiful one liner.Mineralogy
its also returning "." and ".." any better way to skip it in a loop?Amplexicaul
D
5

One liner :-

$arr = glob("*.{jpg,gif,png,bmp}", GLOB_BRACE) 
Dior answered 7/12, 2011 at 11:53 Comment(0)
H
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;
    }
?>
Hassler answered 7/12, 2011 at 11:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.