My team at Spatie is currently building Mailcoach, a solution to self host your e-mail newsletter. Mailcoach can be used as stand alone software or as a Laravel package. Subscribe now at Mailcoach to get a notification as soon as we release it.

Upload large files to S3 using Laravel 5

Original – by Freek Van der Herten – 1 minute read

Chris Blackwell yesterday published a tutorial on how to upload files to S3 using Laravel.

This is the code he used (slightly redacted):

$disk= Storage::disk('s3');

$disk->put($targetFile, file_get_contents($sourceFile));

This is a good way to go about it for small files. You should note that file_get_contents will load the entire file into memory before sending it to S3. This can be problematic for large files.

If you want to upload big files you should use streams. Here's the code to do it:

$disk = Storage::disk('s3');

$disk->put($targetFile, fopen($sourceFile, 'r+'));

PHP will only require a few MB of RAM even if you upload a file of several GB.

You can also use streams to download a file from S3 to the local file system:

$disk = Storage::disk('s3');

$stream = $disk
   ->getDriver()
   ->readStream($sourceFileOnS3);

file_put_contents($targetFile, stream_get_contents($stream), FILE_APPEND);

You can even use streams to copy file from one disk to another without touching the local filesystem:

$stream = Storage::disk('s3')->getDriver()
                             ->readStream($sourceFile);

Storage::disk('sftp')->put($targetFile, $stream);

Stay up to date with all things Laravel, PHP, and JavaScript.

Follow me on Twitter. I regularly tweet out programming tips, and what I myself have learned in ongoing projects.

Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.

Sam Serrien liked on 15th November 2019
Freek Van der Herten replied on 13th November 2019
Think so, yes
nick breens liked on 13th November 2019
Joren Van Hocht replied on 13th November 2019
Laravel Medialibrary is using the same approach if I analysed the code correctly, is it?
Joren Van Hocht liked on 13th November 2019
Joren Van Hocht replied on 13th November 2019
I think this was the first thing I read when searching my self, but still thanks ?