Skip to content

Instantly share code, notes, and snippets.

@kenng
Forked from fideloper/stream_file.php
Created April 13, 2018 02:11
Show Gist options
  • Save kenng/c6732b448a74e81b48157ff9264b89b5 to your computer and use it in GitHub Desktop.
Save kenng/c6732b448a74e81b48157ff9264b89b5 to your computer and use it in GitHub Desktop.
Stream file from S3 to browser, assume Laravel Filesystem usage
<?php
/*************************************************************************
* Get File Information
*/
// Assuming these come from some data source in your app
$s3FileKey = 's3/key/path/to/file.ext';
$fileName = 'file.ext';
// Create temporary download link and redirect
$adapter = Storage::disk('s3')->getAdapter();
$client = $adapter->getClient();
$client->registerStreamWrapper();
$object = $client->headObject([
'Bucket' => $adapter->getBucket(),
'Key' => /*$adapter->getPathPrefix() . */$s3FileKey,
]);
/*************************************************************************
* Set headers to allow browser to force a download
*/
header('Last-Modified: '.$object['LastModified']);
// header('Etag: '.$object['ETag']); # We are not implementing validation caching here, but we could!
header('Accept-Ranges: '.$object['AcceptRanges']);
header('Content-Length: '.$object['ContentLength']);
header('Content-Type: '.$object['ContentType']);
header('Content-Disposition: attachment; filename='.$fileName));
/*************************************************************************
* Stream file to the browser
*/
// Open a stream in read-only mode
if (!($stream = fopen("s3://{$adapter->getBucket()}/{$s3FileKey}", 'r'))) {
throw new \Exception('Could not open stream for reading file: ['.$s3FileKey.']');
}
// Check if the stream has more data to read
while (!feof($stream)) {
// Read 1024 bytes from the stream
echo fread($stream, 1024);
}
// Be sure to close the stream resource when you're done with it
fclose($stream);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment