#Upload a large file to S3 in PHP with a multipart upload
Let's say a nightly job exports all our orders to one CSV file, about 1Gb, and puts it into an S3 bucket.
Our PHP process runs with the default memory_limit of 128Mb.
Doesn't look like a complicated task, right?
The scripts that talk to S3 need a bucket, so they don't run in the playground. Run them on your machine.
#The file
First we need a file to work with, so let's generate one.
Set $rows to 16_500_000 to get the 1Gb version.
<?php
declare(strict_types=1);
$rows = 1_000;
$file = fopen(__DIR__ . '/orders.csv', 'w');
fputcsv($file, ['id', 'email', 'country', 'amount', 'created_at'], escape: '');
for ($id = 1; $id <= $rows; $id++) {
fputcsv($file, [
$id,
"customer{$id}@example.com",
['PL', 'US', 'DE', 'FR', 'GB'][$id % 5],
number_format(($id % 1000) / 10, 2, '.', ''),
gmdate('Y-m-d H:i:s', 1_700_000_000 + $id * 60),
], escape: '');
}
fclose($file);
echo "orders.csv: {$rows} rows\n";
orders.csv: 1000 rows
#Upload a file to S3 with putObject
The first answer we find is putObject from the AWS SDK for PHP.
<?php
declare(strict_types=1);
use Aws\S3\S3Client;
require __DIR__ . '/vendor/autoload.php';
$client = new S3Client(['version' => 'latest', 'region' => 'eu-west-1']);
$client->putObject([
'Bucket' => 'orders-exports',
'Key' => 'exports/orders.csv',
'Body' => file_get_contents(__DIR__ . '/orders.csv'),
]);
With a thousand rows it works. With a 100Mb file it still works, with 126Mb of memory, 2Mb below the limit. With the 1Gb file it ends like this:
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 1114636288 bytes)
#Why putObject runs out of memory
file_get_contents reads the whole file into one string, and putObject sends that string in one request.
For our file that is 1089Mb, and we have 128Mb.
The script that passed every test with a small file fails on the first big export.
We could raise memory_limit, but that only moves the problem to the next, bigger file.
#S3 multipart upload in PHP
A multipart upload cuts the file into parts and sends each part in its own request. S3 puts them together at the end. Only one part is in memory at a time, so it doesn't matter how big the file is.
By hand that is three kinds of requests: one that opens the upload, one for every part, and one that closes it with the list of all parts. We also have to cut the file and keep the number of every part.
#Upload a large file to S3 with Flow
Flow does all of that for us. It needs PHP 8.3 or newer. Its S3 filesystem uses AsyncAws, so the AWS SDK is not needed. The same code works with Azure Blob Storage and with an SFTP server, so from here every example has a tab for each of them.
S3
composer require flow-php/filesystem flow-php/filesystem-async-aws-bridge
Azure Blob Storage
composer require flow-php/filesystem flow-php/filesystem-azure-bridge nyholm/psr7
SFTP
composer require flow-php/filesystem flow-php/filesystem-sftp-bridge
And this is the whole upload:
S3
<?php
declare(strict_types=1);
use function Flow\Filesystem\Bridge\AsyncAWS\DSL\aws_s3_filesystem;
use function Flow\Filesystem\DSL\path;
require __DIR__ . '/vendor/autoload.php';
$storage = aws_s3_filesystem('orders-exports', [
'region' => 'eu-west-1',
'accessKeyId' => $_ENV['AWS_S3_KEY'],
'accessKeySecret' => $_ENV['AWS_S3_SECRET'],
]);
$storage->writeTo(path('aws-s3://exports/orders.csv'))
->fromResource(fopen(__DIR__ . '/orders.csv', 'rb'))
->close();
Azure Blob Storage
<?php
declare(strict_types=1);
use function Flow\Filesystem\Bridge\Azure\DSL\azure_filesystem;
use function Flow\Filesystem\DSL\path;
require __DIR__ . '/vendor/autoload.php';
$storage = azure_filesystem([
'account_name' => $_ENV['AZURE_ACCOUNT'],
'container' => 'orders-exports',
'shared_key' => $_ENV['AZURE_SHARED_KEY'],
]);
$storage->writeTo(path('azure-blob://exports/orders.csv'))
->fromResource(fopen(__DIR__ . '/orders.csv', 'rb'))
->close();
SFTP
<?php
declare(strict_types=1);
use function Flow\Filesystem\Bridge\SFTP\DSL\sftp_filesystem;
use function Flow\Filesystem\DSL\path;
require __DIR__ . '/vendor/autoload.php';
$storage = sftp_filesystem([
'host' => $_ENV['SFTP_HOST'],
'user' => $_ENV['SFTP_USER'],
'password' => $_ENV['SFTP_PASSWORD'],
]);
$storage->writeTo(path('sftp://upload/exports/orders.csv'))
->fromResource(fopen(__DIR__ . '/orders.csv', 'rb'))
->close();
On S3, writeTo opens a multipart upload. Every time 5Mb of data is ready, Flow sends it as one part, and close finishes the upload.
The 1Gb file goes up in 215 requests, with 6Mb of memory.
Azure Blob Storage gets the file the same way, in blocks of 4Mb.
Only the first lines of the script know which storage it is.
#Write to S3 while PHP generates the data
Our job writes orders.csv to the disk only to upload it a moment later.
The stream that writeTo gives us takes data piece by piece, so we can skip the file.
$storage is the filesystem from the script above.
S3
$stream = $storage->writeTo(path('aws-s3://exports/orders-generated.csv'));
Azure Blob Storage
$stream = $storage->writeTo(path('azure-blob://exports/orders-generated.csv'));
SFTP
$stream = $storage->writeTo(path('sftp://upload/exports/orders-generated.csv'));
$rows = 1_000;
$lines = "id,email,country,amount,created_at\n";
for ($id = 1; $id <= $rows; $id++) {
$lines .= implode(',', [
$id,
"customer{$id}@example.com",
['PL', 'US', 'DE', 'FR', 'GB'][$id % 5],
number_format(($id % 1000) / 10, 2, '.', ''),
gmdate('Y-m-d H:i:s', 1_700_000_000 + $id * 60),
]) . "\n";
if ($id % 10_000 === 0) {
$stream->append($lines);
$lines = '';
}
}
$stream->append($lines)->close();
We collect ten thousand lines and append them at once, because one append per line is three times slower.
16.5 million orders go to S3 with 6Mb of memory, and orders.csv never touches our disk.
The next job reads the export back. That's the guide about reading a large file from S3, with the copy to SFTP and Azure at its end.
All the options of each filesystem are in the documentation of the S3, Azure and SFTP bridges.
#How much memory does an S3 upload take in PHP
PHP 8.3, memory_limit=128M, a 1Gb file, aws/aws-sdk-php 3.409. Each number is one run.
The S3 server runs on the same machine, so the times have no network in them.
| Task | Code | Peak memory | Time |
|---|---|---|---|
| Upload | putObject with file_get_contents |
fatal error, needs 1089Mb | - |
| Upload | Flow fromResource |
6Mb | 17.5s |
| Generate and send | Flow append |
6Mb | 26.2s |
The numbers that matter are the ones that don't change. With a 100Mb file every Flow row takes the same memory as with 1Gb.
Only putObject with a string grows with the file: 126Mb for 100Mb, 1089Mb for 1Gb.
To check it on your machine, add this line at the end of any of the scripts above:
printf("peak memory: %.1f MB\n", memory_get_peak_usage(true) / 1024 / 1024);