How get all image names of files in an image folder in php5? after will use php to eject html to view all images of the folder in a web page...

Dani AI

Generated

As noted, PHP already provides file-listing tools — a good gallery workflow is: enumerate the folder, reliably detect which entries are images (not just by extension), sort, then emit safe HTML. For simple cases scandir is fine; for cleaner, object-oriented code or recursion use the SPL iterators. Prefer finfo_file to validate MIME type and fall back to getimagesize if fileinfo isn't available.

Example (safe, PHP5-compatible pattern):

$webDir = 'images';
$fsDir  = dirname(__FILE__) . '/' . $webDir;
$images = array();

if (is_dir($fsDir) && is_readable($fsDir)) {
    foreach (new DirectoryIterator($fsDir) as $file) {
        if ($file->isFile()) {
            $name = $file->getFilename();
            $path = $fsDir . '/' . $name;

            if (function_exists('finfo_open')) {
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                $mime  = finfo_file($finfo, $path);
                finfo_close($finfo);
                if (strpos($mime, 'image/') === 0) $images[] = $name;
            } else {
                if (@getimagesize($path) !== false) $images[] = $name;
            }
        }
    }
}

natsort($images);

foreach ($images as $img) {
    $src = $webDir . '/' . rawurlencode($img);
    echo '<img src="' . htmlspecialchars($src) . '" alt="' . htmlspecialchars($img) . '" />';
}

Notes and cautions: never trust user-supplied paths (normalize and restrict to an allowed base), check is_readable() and is_file() before using files, and escape output with htmlspecialchars() and rawurlencode() for URLs. For large folders use pagination or lazy-loading; if images live outside the web root, stream them through a script with proper caching headers. See the PHP docs for DirectoryIterator, scandir, and getimagesize for more options.

Recommended Answers

All 2 Replies

Have a look at glob.

nice function, help me indirectly
this means i should go over php lib

thx

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.