且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP使用fwrite和fread与输入流

更新时间:2023-12-04 13:13:58

是-以这种方式使用的 fread 首先会读取最多1 GB的字符串,然后通过 fwrite .PHP不够聪明,无法为您创建内存高效的管道.

Yep - fread used in that way would read up to 1 GB into a string first, and then write that back out via fwrite. PHP just isn't smart enough to create a memory-efficient pipe for you.

我会尝试类似于以下的内容:

I would try something akin to the following:

$hSource = fopen('php://input', 'r');
$hDest = fopen(UPLOADS_DIR . '/' . $MyTempName . '.tmp', 'w');
while (!feof($hSource)) {
    /*  
     *  I'm going to read in 1K chunks. You could make this 
     *  larger, but as a rule of thumb I'd keep it to 1/4 of 
     *  your php memory_limit.
     */
    $chunk = fread($hSource, 1024);
    fwrite($hDest, $chunk);
}
fclose($hSource);
fclose($hDest);

如果您想真正变得挑剔,还可以在 fwrite 之后的循环内 unset($ chunk); ,以绝对确保PHP释放内存-但没必要,因为下一个循环将覆盖当时 $ chunk 正在使用的任何内存.

If you wanted to be really picky, you could also unset($chunk); within the loop after fwrite to absolutely ensure that PHP frees up the memory - but that shouldn't be necessary, as the next loop will overwrite whatever memory is being used by $chunk at that time.