Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get filenames of images in a directory

Tags:

php

opendir

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.

like image 808
Hammad Khalid Avatar asked Dec 07 '11 11:12

Hammad Khalid


People also ask

How do I find the filename of an image?

You can view the filename of any image on the internet — here's how. Right click on the image and select “Inspect.” The image HTML should come up — look for the src tag — focus on the unique end slug (highlighted below.) That's the image filename.

How do I get a list of images in a directory in Python?

Below is a list of different approaches that can be taken to solve the List Images In Directory Python problem. import os # specify the img directory path path = "path/to/img/folder/" # list files in img directory files = os. listdir(path) for file in files: # make sure file is an image if file.


2 Answers

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);
    }
}
like image 164
Leonard Avatar answered Oct 15 '22 21:10

Leonard


'scandir' does this:

$images = scandir($dir);
like image 45
Evert Avatar answered Oct 15 '22 23:10

Evert