You were correct to reference the
PHP library tutorial, which pertains to the "mongodb" extension and its userland library. The
MongoGridFS class is from the legacy "mongo" extension.
Following that tutorial and its examples for uploadFromStream and downloadToStream, I produced the following example script which attempts to store itself in GridFS, read it back, and write the copy to a new filename:
<?php
require_once 'vendor/autoload.php';
$client = new MongoDB\Client;
$bucket = $client->test->selectGridFSBucket();
$readFile = fopen(__FILE__, 'rb');
$id = $bucket->uploadFromStream(basename(__FILE__), $readFile);
$writeFile = fopen(__FILE__ . '.copied', 'wb');
$bucket->downloadToStream($id, $writeFile);
If you download this as "foo.php" and run it as a CLI script you should see it generate a "foo.php.copied" file in the same directory. That copy should be identical. Note that uploadFromStream() returns the ID of the uploaded file (an ObjectID is created by default unless you provide a custom ID in the options -- less common).
To your second question of retrieving a GridFS file by name instead of ID, the
Selecting files by filename and revision section in the tutorial provides examples for that behavior. Note that GridFS does not enforce unique filenames. It is nothing more than a string field on the fs.files document, to which you can assign anything. In the example above, we use the
basename() of the PHP source file. Therefore, we could rewrite the script to read the file back by changing the last line:
$bucket->downloadToStreamByName(basename(__FILE__), $writeFile);
As explained in the tutorial, this will search for a file with the given filename string and the most recent timestamp. By convention, files in GridFS with the same filename string are considered revisions of one another -- irrespective of whether their contents are at all similar. A "revision" option can be used to access older versions of a filename, as shown in the tutorial.
Given that revisions are purely convention, there is nothing to stop you from storing a PDF and JPG file under the same name. They will have different upload timestamps and GridFS would consider them to be different revisions for the same filename. For this reason, the best approach will typically be to rely on the unique ID of a file. This is especially true if the filename itself is user-generated (e.g. you're using the same filename from a user-submitted upload).