简体   繁体   中英

Showing a list of images using PHP

I have got a directory which contains several folders with images. What I want to do is to read all the images using php script and showing them with div in a browser. The code I have tried to implement is the following:

<?php

function listFolderFiles($dir) 
{
    echo '<ol>';
    foreach (new DirectoryIterator($dir) as $folder) {
        if (!$folder->isDot()) {
            // echo '<li>' . $folder->getFilename() . '<br>';
            if ($folder->isDir()) {
                $user = $dir . '/' . $folder;
                foreach (new DirectoryIterator($user) as $file) {
                    if ($file != '.' && $file != '..') {
                        // echo '<li>' . $file->getFilename();
                        $image = $user . '/' . $file;

                        echo $image . '<br>'; 

                        echo '<div>';
                        echo '<img src="' . $image . '" width="500" height="500" alt="'; 
                        echo '"/>';
                        echo '</div>';
                    }
                }
            }
            echo '</li>';
        }
    }
    echo '</ol>';
}

listFolderFiles('images');

The command echo $image.'<br>'; prints the names of all images. With the following command I manage to create div, however without the images been displayed inside them:

echo '<div>';
echo '<img src="' . $image . '" width="500" height="500" alt="';
echo '"/>';
echo '</div>';

Am I doing something wrong? The $image paths are correct. EDIT: I move the folder of images in the same folder with the php file in the wamp folder. Now for example the image file is the following images/01virarias/1_.jpg. I change the call of my function as listFolderFiles('images');. However I am getting the same empty divs.

if your path is correct do a inspect element on your browser i think it's quoting issue try

echo '<img src="'. $image .'" width="500" height="500" alt=""/>';

You can use images path relative/absolute like

relative :- ../images/your_image
absolute :-  http://localhost/your_image_path

You need to use an URL. It seems you are using local files. Your browser is the 'problem'. Although it is a matter of security.

The images should be in your server environment.

And it seems you forgot a <li> start tag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM