1 year ago

#314607

test-img

raubvogel

Why does fread() on php://input writes temp files and how to avoid?

The PHP 7.4 (on Windows) code is:

<?php
// index.php

$postBodyResource = fopen("php://input", 'rb');
while (!feof($postBodyResource)) {
    $data = fread($postBodyResource, 5 * 1024);
}
fclose($postBodyResource);

The key part of the Apache 2.4 (on Windows) config is

Alias "/api" "${SRVROOT}/htdocs/Api"
<Directory "${SRVROOT}/htdocs/Api">
    RewriteEngine On 
    RewriteCond %{REQUEST_FILEaNAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ index.php [QSA,L]

    Script POST "index.php"
    Script PUT "index.php"

    php_value enable_post_data_reading Off
</Directory>

If I do a HTTP POST (Content-Type: application/octet-stream) at http://localhost/api with a body larger than 8 kB, PHP creates a temp file at sys_temp_dir that stores the whole content of the stream php://input while doing fread(). Why?

Do we know a method to avoid this behaviour? I want to read the stream without any disk/SSD access – just parts in memory. Finally, I want to get the SHA3-512 hash value of the HTTP body, that can be very large. Therefore writing to temp is a critical bottleneck.

php

post

stream

fread

temp

0 Answers

Your Answer

Accepted video resources