Forked from settermjd/download-file-in-expressive.php
Created
September 9, 2016 01:30
Quick example of how to download/stream a file using Zend Expressive.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* This is a quick example of how to stream a file to a client, likely a browser, | |
* using Zend Expressive. There are a lot of factors which it doesn't take in to | |
* account. But for the purposes of a quick intro, this should suffice. | |
*/ | |
class ViewDocumentPageAction | |
{ | |
protected function downloadFile() | |
{ | |
$file = 'path/to/your/file'; | |
// create a Stream object, to stream your file to the client | |
$body = new Stream('php://temp', 'w+'); | |
$body->write(file_get_contents($file)); | |
// Return a response, containing all of the appropriate headers for | |
// the file that you're sending to the client. You could initialise a | |
// class which does all this for you, instead of having to remember | |
// them all by hand. But I'm keen to provide full transparency in | |
// this example. | |
return $response | |
->withHeader('Content-Type', 'application/octet-stream') | |
->withHeader( | |
'Content-Disposition', | |
"attachment; filename=" . basename($file) | |
) | |
->withHeader('Content-Transfer-Encoding', 'Binary') | |
->withHeader('Content-Description', 'File Transfer') | |
->withHeader('Pragma', 'public') | |
->withHeader('Expires', '0') | |
->withHeader('Cache-Control', 'must-revalidate') | |
->withBody($body) | |
->withHeader('Content-Length', "{$body->getSize()}"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment