繁体   English   中英

PHP使用fwrite和fread与输入流

[英]PHP using fwrite and fread with input stream

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

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内部的fread是否表示整个文件将被加载到内存中?

做相反(将文件写入输出流),PHP提供了一个调用的函数fpassthru我认为不成立的PHP脚本的内存中的文件的内容。

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

以这种方式使用的Yef- fread会读取最多1 GB的字符串,然后再通过fwrite将其写回。 PHP不够聪明,无法为您创建内存高效的管道。

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

$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);

如果您真的想挑剔,也可以unset($chunk); fwrite之后的循环中完全确保PHP释放了内存-但这不是必需的,因为下一个循环将覆盖$chunk当时使用的任何内存。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM