File tree 2 files changed +91
-0
lines changed
2 files changed +91
-0
lines changed Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ /**
4
+ * This example demonstrates how to use GridFS streams.
5
+ */
6
+
7
+ declare (strict_types=1 );
8
+
9
+ namespace MongoDB \Examples ;
10
+
11
+ use MongoDB \Client ;
12
+
13
+ use function fclose ;
14
+ use function feof ;
15
+ use function fread ;
16
+ use function fwrite ;
17
+ use function getenv ;
18
+ use function strlen ;
19
+
20
+ use const PHP_EOL ;
21
+
22
+ require __DIR__ . '/../vendor/autoload.php ' ;
23
+
24
+ $ client = new Client (getenv ('MONGODB_URI ' ) ?: 'mongodb://127.0.0.1/ ' );
25
+
26
+ $ bucket = $ client ->test ->selectGridFSBucket (['disableMD5 ' => true ]);
27
+
28
+ // Open a stream for writing, similar to fopen with mode 'w'
29
+ $ stream = $ bucket ->openUploadStream ('hello.txt ' );
30
+
31
+ for ($ i = 0 ; $ i < 1_000_000 ; $ i ++) {
32
+ fwrite ($ stream , 'Hello line ' . $ i . PHP_EOL );
33
+ }
34
+
35
+ // Last data are flushed to the server when the stream is closed
36
+ fclose ($ stream );
37
+
38
+ // Open a stream for reading, similar to fopen with mode 'r'
39
+ $ stream = $ bucket ->openDownloadStreamByName ('hello.txt ' );
40
+
41
+ $ size = 0 ;
42
+ while (! feof ($ stream )) {
43
+ $ data = fread ($ stream , 2 ** 10 );
44
+ $ size += strlen ($ data );
45
+ }
46
+
47
+ echo 'Read a total of ' . $ size . ' bytes ' . PHP_EOL ;
Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ /**
4
+ * This example demonstrates how to upload and download files from a stream with GridFS.
5
+ */
6
+
7
+ declare (strict_types=1 );
8
+
9
+ namespace MongoDB \Examples ;
10
+
11
+ use MongoDB \Client ;
12
+
13
+ use function fclose ;
14
+ use function fopen ;
15
+ use function fwrite ;
16
+ use function getenv ;
17
+ use function rewind ;
18
+
19
+ use const PHP_EOL ;
20
+ use const STDOUT ;
21
+
22
+ require __DIR__ . '/../vendor/autoload.php ' ;
23
+
24
+ $ client = new Client (getenv ('MONGODB_URI ' ) ?: 'mongodb://127.0.0.1/ ' );
25
+
26
+ $ gridfs = $ client ->selectDatabase ('test ' )->selectGridFSBucket ();
27
+
28
+ // Create an in-memory stream, this can be any stream source like STDIN or php://input for web requests
29
+ $ stream = fopen ('php://temp ' , 'w+ ' );
30
+ fwrite ($ stream , 'Hello world! ' );
31
+ rewind ($ stream );
32
+
33
+ // Upload to GridFS from the stream
34
+ $ id = $ gridfs ->uploadFromStream ('hello.txt ' , $ stream );
35
+ echo 'Inserted file with ID: ' . $ id . PHP_EOL ;
36
+ fclose ($ stream );
37
+
38
+ // Download the file and print the contents directly to STDOUT
39
+ echo 'File contents: ' ;
40
+ $ gridfs ->downloadToStreamByName ('hello.txt ' , STDOUT );
41
+ echo PHP_EOL ;
42
+
43
+ // Delete the file
44
+ $ gridfs ->delete ($ id );
You can’t perform that action at this time.
0 commit comments