Search code examples
phpdownloadslim-3

Slim 3 Framework - How to return a generated file?


In the code snippet below the content of the $file array is rendered in the browser.

The code works but I think there must be a better way to transform the binary string into a stream to send to the browser.

if (is_array($file)) {

    $filename=preg_replace('/[^A-Za-z0-9 \\._-]+/', '', $file['filename']);

    // -- This feels like a hack
    $stream = fopen('php://memory', 'r+');
    fwrite($stream, $file['content']);
    rewind($stream);
    // --

    return $response->withHeader('Content-Type', $file['mimetype'])
        ->withHeader('Content-Transfer-Encoding', 'binary')
        ->withHeader('Content-Disposition', 'inline; filename="' . basename($filename) . '"')
        ->withHeader('Expires', '0')
        ->withHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
        ->withHeader('Pragma', 'public')
        ->withBody(new \Slim\Http\Stream($stream));
}

What is the proper way to transform the content into a stream?


Solution

  • Problem solved by using the Response object’s getBody() method.

    if (is_array($file)) {
    
        if (strlen($file['filename'])) {
            $filename=preg_replace('/[^A-Za-z0-9 \\._-]+/', '', $file['filename']);
        }
    
        $content = $response->getBody();
        $content->write($file['content']);
    
        return $response->withHeader('Content-Type', $file['mimetype'])
            ->withHeader('Content-Transfer-Encoding', 'binary')
            ->withHeader('Content-Disposition', 'inline; filename="' . basename($filename) . '"')
            ->withHeader('Expires', '0')
            ->withHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
            ->withHeader('Pragma', 'public');
    
    }