1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
use Slim\Psr7\Stream;
/*
* Stream a temp file. Delete it when finished
*/
class TempStream extends Stream
{
private $filename;
public function __construct($filename)
{
$this->filename = $filename;
$fh = fopen($filename, 'rb');
parent::__construct($fh);
}
public function __destruct()
{
unlink($this->filename);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
use Slim\Http\Request;
use Slim\Http\Response;
use Slim\Http\Stream;
$app->get('/stream', function (Request $request, Response $response, array $args) {
$tmpfname = tempnam("/tmp");
// write data to tmpfname (eg. create a zip)
// ...
// TempStream gets the filename as parameter, not
// the resource
$file_stream = new TempStream($tmpfname);
return $response->withBody($file_stream)
->withHeader('Content-Disposition', 'attachment; filename=document.pdf;')
->withHeader('Content-Type', mime_content_type($tmpfname))
->withHeader('Content-Length', filesize($tmpfname));
})->setOutputBuffering(false);