0

I am using GridFS and I have currently got it to display a single image using findOne, although I would like it to iterate through all the results in the grid and echo them all to screen, here is the code I am using:

<?php
try {
  // open connection to MongoDB server
  $conn = new Mongo;

  // access database
  $db = $conn->database;

  // get GridFS files collection
  $grid = $db->getGridFS();

  // retrieve file from collection
  header('Content-type: image/png');
  $file = $grid->findOne(array('_id' => new MongoId('4fb437dbee3c471b1f000001')));

  // send headers and file data

  echo $file->getBytes();
  exit;  

  // disconnect from server
  $conn->close();
} catch (MongoConnectionException $e) {
  die('Error connecting to MongoDB server');
} catch (MongoException $e) {
  die('Error: ' . $e->getMessage());
}
?>

Thanks

Community
  • 1
  • 1

3 Answers3

0

Use "find" vs "findOne", which will return a result set you can loop through with a foreach, like:

$files = $grid->find({});

foreach($files as $file) { echo $file->someData; }

jbnunn
  • 6,161
  • 4
  • 40
  • 65
  • I tried this $files = $grid->find(); foreach($files as $file) { echo $file->getBytes(); } although it didn't work –  May 17 '12 at 17:59
  • If you want all the files, try find({}) (notice the braces as empty parameters). And, instead of showing the $file->getBytes(); in your loop, try "print_r($file);" just to debug to see if you get anything. – jbnunn May 17 '12 at 20:18
0

In general, if you're displaying images on a web page, you want to have a bunch of tags like <img src="someUrl" /> and then have each someUrl handle getting a single image.

kris
  • 23,024
  • 10
  • 70
  • 79
0

You set the header to image/png so the browser expects only one image.

What you could do is change that to a text/html document and embed the images using the data URI scheme (see http://en.wikipedia.org/wiki/Data_URI_scheme ) and then output the images in a series of images tags.

<!doctype html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>My images</title>
    <head>
    <body>
    <?php
    /* ... db connection/init code ... */

    $files = $grid->find({});

    foreach($files as $file) { 
       $encodedData = base64_encode($file->getBytes());
       echo "<img src=\"data:image/png;base64,{$encodedData}\">";
       echo "<br>";
    }
    ?>
    </body>
</html>

Note that you probably want to detect if the mime type of the image and change accordingly and set alt, width and height attributes using the file's metadata.

Hope this helps.

Patrick Forget
  • 2,143
  • 1
  • 18
  • 20