Understanding Why Stream Uploads in PHP Are Memory Efficient
Contents
I had heard that "reading a whole image into memory is memory inefficient", but I had never measured how big the difference really is. This time I wrote a small PHP server that relays received images to external storage and compared memory usage.
It is a relay that only receives images from a browser or app and passes them on to external storage such as S3, Azure Blob, or Supabase Storage. As a diagram, it looks like this.
Mermaid source
flowchart LR
A[Client] -- Image --> B["Relaying PHP<br/>(how memory is used here is the focus)"]
B -- Transfer --> C[External storage]This relay does not save the file. It only receives the file and passes it on, so "how it holds the received content" directly determines memory usage.
What I want to check in this test is "how PHP holds the received image data in memory".
With a raw body (sending the image unmodified as the request body), you only have to switch in code between reading php://input all at once (buffer) or a little at a time (stream). So I tested with a raw body this time.
Note 1: When multipart/form-data also has a memory problem
A form submission with <input type="file"> is multipart/form-data. Its content is structured differently from a raw body, and PHP handles it differently too.
| raw body | multipart/form-data | |
|---|---|---|
| Body content | The image bytes as is | Multiple parts separated by a boundary |
| PHP's automatic processing | None | Parses it automatically, writes files out to temporary files (tmp), and builds $_FILES |
| Memory accumulation by default | None (depends on how you read it) | None (the SAPI streams it to disk) |
| Where the memory problem appears | file_get_contents('php://input') |
file_get_contents($_FILES['x']['tmp_name']) |
php://input |
Usable (a stream source) | Not usable (it is empty) |
There are two points I want to keep in mind.
By default, multipart files do not pile up in memory. PHP (the SAPI) streams them to a temporary file as it receives them. Memory blows up when you read that tmp file whole yourself with file_get_contents(). The other point is that php://input is empty for multipart. PHP consumes the body first to parse it.
To truly handle multipart as a stream, you have to stop automatic parsing with enable_post_data_reading = 0 (it must take effect before the request is received, so you cannot change it with ini_set()) and parse php://input yourself as raw multipart. That is fairly heavy work.
Note 2: An example of the sending side
The sending side (here, `fetch` on the frontend) is written like this.fetch('http://localhost:8080/index.php?mode=stream', {
method: 'PUT',
headers: { 'Content-Type': file.type }, // e.g. image/jpeg
body: file, // Send the File/Blob as the body as is
});
The only difference between buffer and stream is these few lines that change how the request body is read (I left out the measurement code. I describe how I measured later).
// buffer
$data = file_get_contents('php://input'); // Read it all into memory
$uploader->upload($path, $data, $contentType, strlen($data));
// stream
$in = fopen('php://input', 'rb'); // Only open it. Then pass it on while reading
$uploader->upload($path, $in, $contentType, $contentLength);
buffer reads everything with file_get_contents and then passes it to $uploader.
stream passes the handle opened with fopen to $uploader as is.
The difference comes from how PHP strings work.
file_get_contents reads php://input to the end and returns the content as a single PHP string.
A string holds all its bytes as one contiguous value, so a 100MB body puts a 100MB string in memory. This counts directly against memory_limit.
memory_limit is the upper limit of memory one request can allocate.
If you try to allocate beyond it, execution stops right there with Fatal error: Allowed memory size ... exhausted.
file_get_contents grows the string while reading the body, so it does not allocate 100MB at once. It fails partway through reading, at the point where the allocation goes over 64M. This is why buffer fails.
Stream does not turn the content into a string. fopen only opens a handle.
When sending, Guzzle (cURL inside it) repeatedly reads a little into a small fixed-size buffer and sends it. The size of this buffer depends on the environment, but it is around a few KB to a few tens of KB.
It reuses the same buffer, so only one chunk of the body is ever in memory. That is why the peak does not grow no matter how many MB the file is.
Mermaid source
flowchart LR
subgraph BUF["buffer (proportional to size)"]
direction LR
a1["Client"] -->|"100MB"| a2["PHP memory<br/>holds all 100MB"]
a2 -->|"100MB"| a3["Storage"]
end
subgraph STR["stream (constant peak)"]
direction LR
b1["Client"] -->|"100MB"| b2["PHP memory<br/>reuses a few KB"]
b2 -->|"one chunk at a time"| b3["Storage"]
endI called memory_reset_peak_usage at the start of processing and read the peak with memory_get_peak_usage at the end.
The conditions were memory_limit=64M, and the destination was a dummy that discards to /dev/null (to look only at memory on the receiving side).
| File | buffer peak | stream peak |
|---|---|---|
| 1MB | 3.3MB | 2.3MB |
| 10MB | 12.3MB | 2.3MB |
| 50MB | 52.3MB | 2.3MB |
| 100MB | Failed (exceeded memory_limit) | 2.3MB |
The buffer peak grows almost in proportion to the file size. The peak is almost the file size itself, which shows that the string it read is consuming memory directly.
That is why it went over memory_limit and failed at 100MB.
Stream stays constant at around 2.3MB at every size. This is because it does not hold the request body, and I found that the peak did not change as the size grew.
I found that buffer holds as much memory as the file, so it eventually hits memory_limit, while stream does not hold it, so its memory usage stays constant regardless of file size.
Not only with raw bodies, I think that when handling uploads, keeping "don't read everything at once, stream what you can" in mind makes you less likely to be thrown around by file size.
Translated from the Japanese original.
Thanks. I'll look into it.
Sorry, that didn't go through. Please try again later.