Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to save files on MongoDB using PHP?

Tags:

php

mongodb

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

like image 604
fnaquira Avatar asked Mar 06 '26 01:03

fnaquira


1 Answers

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();

?>
like image 147
Eve Freeman Avatar answered Mar 08 '26 16:03

Eve Freeman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!