为什么 php://input 上的 fread() 会写入临时文件以及如何避免?

发布于 2025-01-16 03:00:10 字数 1054 浏览 4 评论 0原文

PHP 7.4(在 Windows 上)代码是:

<?php
// index.php

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

Apache 2.4(在 Windows 上)配置的关键部分是

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>

如果我执行 HTTP POST (Content-Type: application/octet-stream< /code>) 在 http://localhost/api 处,主体大于 8 kB,PHP 在 sys_temp_dir 处创建一个临时文件,用于存储流的全部内容php://input 在执行 fread() 时。为什么?

我们知道避免这种行为的方法吗?我想在没有任何磁盘/SSD 访问的情况下读取流 – 只是内存中的部分。最后,我想获取 HTTP 正文的 SHA3-512 哈希值,该值可能非常大。因此写入 temp 是一个关键瓶颈。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文