fnaquira
fnaquira

Reputation: 342

how to save files on MongoDB using PHP?

how can i save a file on my MongoDB?
I am using PHP and it doesn't seem to be any information..
Also if you coud give me some example to know how to save and download those fles i'll be very thank

Upvotes: 3

Views: 7709

Answers (1)

Eve Freeman
Eve Freeman

Reputation: 33175

Check this tutorial out: http://learnmongo.com/posts/getting-started-with-mongodb-gridfs/

Pasting some code to have it in the answer:

<?php

// Connect to Mongo and set DB and Collection
$mongo = new Mongo();
$db = $mongo->myfiles;

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

// The file's location in the File System
$path = "/tmp/";

$filename = "03-smbd-menu-screen.mp3";

// Note metadata field & filename field
$storedfile = $grid->storeFile($path . $filename,
             array("metadata" => array("filename" => $filename),
             "filename" => $filename));


// Return newly stored file's Document ID
echo $storedfile;

?>

To get a file back out:

<?php
// Connect to Mongo and set DB and Collection
$mongo = new Mongo();
$db = $mongo->myfiles;     

// GridFS
$gridFS = $db->getGridFS();     

// Find image to stream
$image = $gridFS->findOne("chunk-screaming.jpg");

// Stream image to browser
header('Content-type: image/jpeg');
echo $image->getBytes();

?>

Upvotes: 13

Related Questions