6.3.3. MongoDB6.3.3.1. Installation
sudo pecl install MONGO
Vim/srv/php/etc/conf.d/mongo.iniextension=mongo.so
6.3.3.2. Gridfs6.3.3.2.1. Uploading Files
<?php$connection = new Mongoclient ("Mongodb://neo:[email protected]"); $db = $connection->test; $grid = $db Getgridfs (); $id = $grid->put ("/etc/passwd");
6.3.3.2.2. Reading files
<?php$connection = new Mongoclient ("Mongodb://neo:[email protected]"); $db = $connection->test; $grid = $db Getgridfs (); $id = $grid->put ("/etc/passwd"); $oid = new MongoId ($id); $file = $grid->get ($oid); Echo $file GetBytes ();
6.3.3.2.3. StoreFile
StoreFile is similar to put
<?php$connection = new Mongoclient ("Mongodb://neo:[email protected]"); $db = $connection->test; $grid = $db Getgridfs (); $storedfile = $grid->storefile ("/etc/passwd", Array ("date" = new Mongodate ()));//Return newly Stored file ' s Document idecho $storedfile;
6.3.3.2.4. finding files
FindOne is similar to get, get can only take out files by ID, FindOne can find filenames, dates, dimensions, and MD5 values.
<?php$connection = new Mongoclient ("Mongodb://neo:[email protected]"); $db = $connection->test; $grid = $db Getgridfs (); $file = $grid->findone ("/etc/passwd"); Echo $file->getbytes ();
Specify collections
<?php$images = $db->mydb->getgridfs (' images '); $image = $images->findone (' jwage.png '); Header (' content-type:image/png; '); echo $image->getbytes ();? >
6.3.3.2.5. traversing files
FindOne always returns only one piece of data, find can return a result set and implement traversal files.
<?php$connection = new Mongoclient ("Mongodb://neo:[email protected]"); $db = $connection->test; $grid = $db Getgridfs (); $files = $grid->find (); foreach ($files as $file) {print_r ($file);}
This article is excerpted from "Netkiller PHP Codex"
Http://netkiller.github.io/php/index.html
PHP + MongoDB + Gridfs