Dumbo
Dumbo

Reputation: 14132

Get list of all image files in a directory

I am trying to generate some HTML code to list some images for a slide show.

I arrived at the following idea:

function galGetTopPhotos()
{
    //path to directory to scan
    $directory = SITE_ROOT_PATH."/gallery/best/";

    //get all files
    $images = glob($directory . "*.*");

    //print each file name
    $ret = "";
    $ret .= '<div id="myslides">';        

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

    $ret .= '</div>';

    return $ret;
}

The problem is that it only works when I use root path for $directory...if I use URL it will not work. And it causes the images to not load. Here is what this code generates:

<div id="myslides">
<img src="D:/xampp/htdocs/mrasti/gallery/best/1.jpg" />
<img src="D:/xampp/htdocs/mrasti/gallery/best/10.jpg" />
</div>

So the question is, how to get the list of files so it generates img sources in http://127.0.0.1/.... format?

What I mean if I use the code like this it returns no file!

$directory ="http://127.0.0.1/mrasti/gallery/best/";

Upvotes: 0

Views: 8604

Answers (3)

tonymarschall
tonymarschall

Reputation: 3882

glob does only work for local files and not on remote files. Have a look here:

http://php.net/manual/en/function.glob.php

For remote files have a look here:

http://www.php.net/manual/en/features.remote-files.php

But i do not think that you need remote files. It seems like you want to go through a local directory and display this images.

Try something like this

...
$ret .= '<img src="http://127.0.0.1/my/path/'.basename($image).'" />';
...

Upvotes: 2

James Ravenscroft
James Ravenscroft

Reputation: 375

This looks like a job for PHP function basename. This takes a file path and returns only the final element of the path - in this case the actual name of the jpeg image.

You could amend your code so that it looks something like this:

$urlPath = "http://127.0.0.1/mrasti/gallery/best/";

...
...

foreach($images as $image)
{
    $relative_path = $urlPath.basename($image);
    $ret .= '<img src="'.$relative_path.'" />';
}

The above takes the path and appends the filename "example.jpg" to your image directory url

Upvotes: 4

hakre
hakre

Reputation: 198227

You need to have some functionality to translate the file path on disk to the correct URI so that your browser can understand it.

In your specific case as outlined and with the exact data given in your question, the following could work:

foreach($images as $image)
{
    $src = '/mrasti/gallery/best/'.substr($image, strlen($directory));
    $ret .= '<img src="'.$src.'" />';
}

Upvotes: 1

Related Questions