Skip to content

Commit dbea7a3

Browse files
committed
add stream proxying example
1 parent 00ab266 commit dbea7a3

2 files changed

Lines changed: 33 additions & 0 deletions

File tree

user_guide_src/source/outgoing/response.rst

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,15 @@ total size (for example, when proxying a stream of known length), you may set
284284
which sends proper ``Content-Length`` and ``Content-Disposition`` headers.
285285
Use ``StreamResponse`` when the content is generated while it is being sent.
286286

287+
Example: Proxying an Upstream Stream
288+
------------------------------------
289+
290+
``StreamResponse`` can forward a stream from another source - such as object
291+
storage or an internal API - to the client without buffering it in memory or
292+
writing it to disk:
293+
294+
.. literalinclude:: response/041.php
295+
287296
The :ref:`development server <sse-development-server>` and
288297
:ref:`production <sse-production>` considerations described for SSE below apply
289298
to all streaming responses.
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php
2+
3+
use CodeIgniter\HTTP\StreamResponse;
4+
5+
$stream = $this->response->stream(static function (StreamResponse $stream) {
6+
// Forward the upstream file chunk by chunk, without buffering it in memory
7+
$source = fopen('https://storage.internal/reports/annual.pdf', 'rb');
8+
9+
try {
10+
while (! feof($source)) {
11+
$chunk = fread($source, 1_048_576);
12+
13+
if ($chunk === false || ! $stream->write($chunk)) {
14+
break;
15+
}
16+
}
17+
} finally {
18+
fclose($source);
19+
}
20+
});
21+
22+
$stream->setContentType('application/pdf');
23+
24+
return $stream;

0 commit comments

Comments
 (0)