PHPackages                             helmich/gridfs - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. helmich/gridfs

ActiveLibrary[Database &amp; ORM](/categories/database)

helmich/gridfs
==============

GridFS implementation for the MongoDB PHP extension

v1.0.0(10y ago)812.3k1[1 issues](https://github.com/martin-helmich/php-gridfs/issues)MITPHPPHP &gt;=7.0.0

Since Feb 21Pushed 9y ago2 watchersCompare

[ Source](https://github.com/martin-helmich/php-gridfs)[ Packagist](https://packagist.org/packages/helmich/gridfs)[ RSS](/packages/helmich-gridfs/feed)WikiDiscussions master Synced 4w ago

READMEChangelogDependencies (5)Versions (2)Used By (0)

GridFS implementation for the PHP MongoDB driver
================================================

[](#gridfs-implementation-for-the-php-mongodb-driver)

[![Build Status](https://camo.githubusercontent.com/7057d940781ba6cb330ef5069bef905971046cd77a9a862618eb7c02792a24db/68747470733a2f2f7472617669732d63692e6f72672f6d617274696e2d68656c6d6963682f7068702d6772696466732e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/martin-helmich/php-gridfs)[![Code Climate](https://camo.githubusercontent.com/bdcb13178dc218912bf91508beb54583d1ae35bb22f144f33cb5d5aba673eda6/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f6d617274696e2d68656c6d6963682f7068702d6772696466732f6261646765732f6770612e737667)](https://codeclimate.com/github/martin-helmich/php-gridfs)[![Issue Count](https://camo.githubusercontent.com/00396a64787ed536f7e2a2a2619c7355bff203f87dc158ebc2971cfe11431b25/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f6d617274696e2d68656c6d6963682f7068702d6772696466732f6261646765732f69737375655f636f756e742e737667)](https://codeclimate.com/github/martin-helmich/php-gridfs)[![Test Coverage](https://camo.githubusercontent.com/43236dc91ecfcede246650250f819fe9ae101c00131bbaa520d321ca5ce01061/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f6d617274696e2d68656c6d6963682f7068702d6772696466732f6261646765732f636f7665726167652e737667)](https://codeclimate.com/github/martin-helmich/php-gridfs/coverage)

This package provides a userspace implementation of the [GridFS specification](https://github.com/mongodb/specifications/blob/master/source/gridfs/gridfs-spec.rst) for PHP's new [`mongodb`](http://php.net/manual/en/set.mongodb.php) extension (not to be confused with the similarly named `mongo` extension).

**This library requires PHP 7!**

Author and license
------------------

[](#author-and-license)

Martin Helmich
This library is [MIT-licensed](LICENSE.txt).

Installation
------------

[](#installation)

Use [Composer](http://getcomposer.org):

```
$ composer require helmich/gridfs

```

Usage
-----

[](#usage)

### Initialization

[](#initialization)

GridFS is oriented around *Buckets*. For a bucket named `$name`, this library will create two collections `$name.files` and `$name.chunks` in which file metadata and content blocks will be stored. Create a new bucket by instantiating the `Helmich\GridFS\Bucket` class. You will need a `MongoDB\Database` instance as dependency and can optionally pass an instance of the `Helmich\GridFS\Options\BucketOptions` class to configure your bucket:

```
$manager = new \MongoDB\Driver\Manager('mongodb://localhost:27017');
$database = new \MongoDB\Database($manager, 'yourdatabase');

$bucketOptions = (new \Helmich\GridFS\Options\BucketOptions)
  ->withBucketName('yourbucket');
$bucket = new \Helmich\GridFS\Bucket($database, $bucketOptions);
```

### Uploading files into a bucket

[](#uploading-files-into-a-bucket)

Uploading of files is done via streams. You can open a new upload stream using the `openUploadStream` function:

```
$uploadOptions = (new \Helmich\GridFS\Options\UploadOptions)
  ->withChunkSizeBytes(4 withMetadata(['foo' => 'bar']);

$uploadStream = $bucket->openUploadStream("helloworld.txt", $uploadOptions);
$uploadStream->write("Hello World!");
$uploadStream->close();

echo "File ID is: " . $uploadStream->fileId();
```

Alternatively, use the `uploadFromStream` method, which takes a PHP stream as a parameter:

```
$fileStream = fopen('humungousfile.blob', 'r');
$fileId = $bucket->uploadFromStream('humungousfile.blob', $fileStream, $uploadOptions);
```

### Finding uploaded files

[](#finding-uploaded-files)

Use the `find` method to find files in your bucket. The `find` method takes a MongoDB query object as first parameter that is applied to the `$bucketName.files` collection. The second parameter is an instance of the `Helmich\GridFS\Options\FindOptions` class in which you can specify advanced options for the search:

```
$options = (new \Helmich\GridFS\Options\FindOptions)
  ->withBatchSize(32)
  ->withLimit(128)
  ->withSkip(13)
  ->withSort(['filename' => 1])
  ->withNoCursorTimeout();

$query = [
  'filename' => [
    '$in': ['foo.txt', 'bar.txt']
  ],
  'uploadDate' => [
    '$gt' => new \MongoDB\BSON\UTCDatetime(time() - 86400)
  ]
];

$files = $bucket->find($query, $options);
```

### Downloading files from a bucket

[](#downloading-files-from-a-bucket)

Downloading files is also stream-oriented. Given the ID of an already existing file, open a new download stream using the `openDownloadStream` function:

```
$file = $bucket->find(['filename' => 'foo.txt'], (new \Helmich\GridFS\Options\FindOptions)->withLimit(1))[0];

$downloadStream = $bucket->openDownloadStream($file['_id']);
echo $downloadStream->readAll();

// alternatively:
while (!$downloadStream->eof()) {
  echo $downloadStream->read(4096);
}
```

Given an already existing (and writeable) PHP stream, you can also use the `downloadToStream` method to pipe the file directly into the stream:

```
$fileStream = fopen('humungousfile.blob', 'w');
$bucket->downloadToStream($id, $fileStream);
```

There is also a `byName` variant of both `openDownloadStream` (`openDownloadStreamByName()`) and `downloadToStream` (`downloadToStreamByName`). Both of these functions take a file name and a `Helmich\GridFS\Options\DownloadOptions` instance as parameter. The `$options` parameter allows you to specify which revision of the given filename should be downloaded:

```
$options = (new \Helmich\GridFS\Options\DownloadByNameOptions)
  ->withRevision(-1); // also the default; will download the latest revision of the file

$stream = $bucket->openDownloadStreamByName('yourfile.txt', $options);
```

### Deleting files

[](#deleting-files)

Delete files from the bucket using the `delete` method:

```
$bucket->delete($fileId);
```

Gimmicks
--------

[](#gimmicks)

### PSR-7 adapters

[](#psr-7-adapters)

I've implemented this package for a [PSR-7 compliant](http://www.php-fig.org/psr/psr-7/) web application. PSR-7 also heavily relies on streams, so I've found it useful to add an adapter class to map a `Helmich\GridFS\Stream\DownloadStreamInterface` to a `Psr\Http\Message\StreamInterface`. This is especially useful if you want to return GridFS files as a response body stream. The following example uses the [Slim framework](http://www.slimframework.com/), but should be easily adaptable to other PSR-7 compliant frameworks:

```
$app->get(
  '/documents/{name}',
  function(RequestInterface $req, ResponseInterface $res, array $args) use ($bucket): ResponseInterface
  {
    $stream = $bucket->openDownloadStreamByName($args['name']);
    return $res
      ->withHeader('content-type', $stream->file()['metadata']['contenttype'])
      ->withBody(new \Helmich\GridFS\Stream\Psr7\DownloadStreamAdapter($stream));
  }
);
```

###  Health Score

31

—

LowBetter than 66% of packages

Maintenance18

Infrequent updates — may be unmaintained

Popularity27

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

3782d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/38724147?v=4)[helmich](/maintainers/helmich)[@helmich](https://github.com/helmich)

---

Top Contributors

[![martin-helmich](https://avatars.githubusercontent.com/u/2538958?v=4)](https://github.com/martin-helmich "martin-helmich (24 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/helmich-gridfs/health.svg)

```
[![Health](https://phpackages.com/badges/helmich-gridfs/health.svg)](https://phpackages.com/packages/helmich-gridfs)
```

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k8.4M91](/packages/mongodb-laravel-mongodb)[doctrine/mongodb-odm

PHP Doctrine MongoDB Object Document Mapper (ODM) provides transparent persistence for PHP objects to MongoDB.

1.1k24.5M350](/packages/doctrine-mongodb-odm)[alcaeus/mongo-php-adapter

Adapter to provide ext-mongo interface on top of mongo-php-library

47012.6M74](/packages/alcaeus-mongo-php-adapter)[leroy-merlin-br/mongolid

Easy, powerful and ultrafast ODM for PHP and MongoDB.

11135.2k6](/packages/leroy-merlin-br-mongolid)[facile-it/mongodb-bundle

Bundle service integration of official \[mongodb/mongo-php-library\](https://github.com/mongodb/mongo-php-library) driver library

38231.7k1](/packages/facile-it-mongodb-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
