Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create a streaming download of a large file with Slim PHP using the build in Stream class
<?php
use Slim\Http\Request;
use Slim\Http\Response;
use Slim\Http\Stream;
$app->get('/stream', function (Request $request, Response $response, array $args) {
// a 100mb file
$path = '../public/files/document.pdf';
$fh = fopen($path, 'rb');
$file_stream = new Stream($fh);
return $response->withBody($file_stream)
->withHeader('Content-Disposition', 'attachment; filename=document.pdf;')
->withHeader('Content-Type', mime_content_type($path))
->withHeader('Content-Length', filesize($path));
})->setOutputBuffering(false);
@CatatalSP

This comment has been minimized.

Copy link

CatatalSP commented Jan 27, 2020

Thank you, you saved my day!

$type = $args['tipo'] == '2' ? 'attachment' : 'inline';
$fh = fopen($file, 'rb');
$file_stream = new Stream($fh);
return $response->withHeader('Cache-Control', 'private')
->withHeader('Content-Type', mime_content_type($file))
->withHeader('Content-Length', filesize($file))
->withHeader('Content-Disposition', $type.'; filename=' . basename($file))
->withHeader('Accept-Ranges', filesize($file))
->withHeader('Expires', '0')
->withBody($file_stream);<

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.