PHP使用fwrite和fread与输入流 [英] PHP using fwrite and fread with input stream

查看:85
本文介绍了PHP使用fwrite和fread与输入流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找最有效的方法,以将PHP输入流的内容写入磁盘,而不使用授予PHP脚本的大量内存.例如,如果可以上传的最大文件大小为1 GB,但PHP仅具有32 MB内存.

I'm looking for the most efficient way to write the contents of the PHP input stream to disk, without using much of the memory that is granted to the PHP script. For example, if the max file size that can be uploaded is 1 GB but PHP only has 32 MB of memory.

define('MAX_FILE_LEN', 1073741824); // 1 GB in bytes
$hSource = fopen('php://input', 'r');
$hDest = fopen(UPLOADS_DIR.'/'.$MyTempName.'.tmp', 'w');
fwrite($hDest, fread($hSource, MAX_FILE_LEN));
fclose($hDest);
fclose($hSource);

像上面的代码那样在fwrite内部进行读取是否表明整个文件都将被加载到内存中?

Does fread inside an fwrite like the above code shows mean that the entire file will be loaded into memory?

相反,PHP提供了一个名为

For doing the opposite (writing a file to the output stream), PHP offers a function called fpassthru which I believe does not hold the contents of the file in the PHP script's memory.

我正在寻找类似但相反的东西(将 from 输入流写入文件).感谢您提供的任何帮助.

I'm looking for something similar but in reverse (writing from input stream to file). Thank you for any assistance you can give.

推荐答案

是-以这种方式使用的 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.

这篇关于PHP使用fwrite和fread与输入流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆