PHP code example of helmich / gridfs

1. Go to this page and download the library: Download helmich/gridfs library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

helmich / gridfs example snippets


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

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

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

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

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

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

$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);
}

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

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

$bucket->delete($fileId);

$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));
  }
);