1

In my parent directory I have an index.php file and I have 15 images in a directory named "images". I want to read the filenames and display the images in the browser. Right now I'm just trying to display the filename in a paragraph tag but nothing is happening. I got this code from the first answer in this thread Getting the names of all files in a directory with PHP

<body>
<?php

    $dir = "Challenge8/images";

    foreach(glob($dir.'/*.*') as $file) {
        echo "<p>filename:" . $file . "</p>";
    }   
?>
</body>

EDIT: I went to FileZilla and copied the entire path and it worked. Can anyone explain why this made a difference? The end location was still "/Challenge8/images"

Community
  • 1
  • 1
  • 1
    i would guess the path is wrong –  Oct 25 '16 at 23:03
  • Thank you for actually giving me feedback and not just downvoting –  Oct 25 '16 at 23:07
  • if images is one up from index `images/*.*` should be the full path –  Oct 25 '16 at 23:10
  • "/Challenge8/images" is not the same path as "Challenge8/images" note the slash, the first is relative to the root, the latter relative to the script location. if your in `/fish/cat` the former searches is `Challenge8/images` the latter in `/fish/cat/Challenge8/images` –  Oct 25 '16 at 23:13

1 Answers1

0

Directory structure:

.
|-- example
|   `-- list_images.php
|-- images
|   |-- bar.jpg
|   |-- baz.jpg
|   `-- foo.jpg
`-- index.php

list_images.php

<?php
$dir = __DIR__ . '/../images';
foreach(glob($dir.'/*.*') as $file) {
     printf("filename:%s\n", $file);
} 

Output of list_images.php:

filename:/var/www/example/../images/bar.jpg
filename:/var/www/example/../images/baz.jpg
filename:/var/www/example/../images/foo.jpg

Note that these are file system paths.

To turn the above into publicly accessible paths, you'll want to output something like:

<img src="/images/<?= basename($file); ?>">
Progrock
  • 7,373
  • 1
  • 19
  • 25