为什么 php://input 上的 fread() 会写入临时文件以及如何避免?
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论