Moorby123
Moorby123

Reputation: 81

PHP: Pull all images from a specified directory using relative image path

I am trying to create a gallery where images are automatically pulled from a images directory.

When I foreach() each image it returns however it pulls the entire root path as the image src

/home/dev/public_html/assets/images/

this causes the images not to show and shows dead linked images on screen. I need the relative path like this:

/assets/images/imagename.jpg

How would I set a base path/URL?

$dirname = "/home/dev/public_html/assets/images/";                              

$images = glob($dirname."*.jpg");

foreach($images as $image) {
    echo '<img src="'.$image.'" /><br />';
}

I tried setting $dirname to this

$dirname = "/assets/images/"; 

But I get no result and nothing pulls through at all.

The file i am creating this in, is located outside the public_html folder, i believe this could be casing the issue but the file cannot be relocated.

Upvotes: 3

Views: 2421

Answers (2)

Sir_Faenor
Sir_Faenor

Reputation: 897

I would edit the loop in order to remove unnecessary string from path:

foreach($images as $image) {
    $src = str_replace('/home/dev/public_html' ,'', $image) ;   
    echo '<img src="'.$src.'" /><br />';
}

Upvotes: 2

Twinfriends
Twinfriends

Reputation: 1987

You could may make use of scandir() http://php.net/manual/en/function.scandir.php

Somethink like:

Edit: Changed the code a bit, so scandir only take files, otherwise the first two placed in the array are folders for the parent folders.

$dir = "assets/images/";
$images = scandir($dir);

foreach($images as $image) {
     if($image != '.' && $image != '..') {
          echo ' <img src="assets/images/'.$image.'"><br>';
     }
}

Hope this helped. If not, let me know, so I can change my answer. But I think it should be fine, as far as I understood what you're trying.

Upvotes: 0

Related Questions