在PHP中将大文件写入磁盘的最佳方法是什么?

Joe*_*oni 14 php file-io file fwrite

我有一个PHP脚本偶尔需要将大文件写入磁盘.使用file_put_contents(),如果该文件是足够大(大约2 MB这种情况下),PHP脚本运行的内存(PHP致命错误:用尽########字节允许内存大小).我知道我可以增加内存限制,但这对我来说似乎不是一个完整的解决方案 - 必须有更好的方法,对吧?

在PHP中将大文件写入磁盘的最佳方法是什么?

Lin*_*een 15

您需要一个临时文件,您可以在其中放置源文件的位以及要附加的内容:

$sp = fopen('source', 'r');
$op = fopen('tempfile', 'w');

while (!feof($sp)) {
   $buffer = fread($sp, 512);  // use a buffer of 512 bytes
   fwrite($op, $buffer);
}

// append new data
fwrite($op, $new_data);    

// close handles
fclose($op);
fclose($sp);

// make temporary file the new source
rename('tempfile', 'source');
Run Code Online (Sandbox Code Playgroud)

这样,整个内容source都不会被读入内存.使用cURL时,可能会省略设置CURLOPT_RETURNTRANSFER,而是添加一个写入临时文件的输出缓冲区:

function write_temp($buffer) {
     global $handle;
     fwrite($handle, $buffer);
     return '';   // return EMPTY string, so nothing's internally buffered
}

$handle = fopen('tempfile', 'w');
ob_start('write_temp');

$curl_handle = curl_init('http://example.com/');
curl_setopt($curl_handle, CURLOPT_BUFFERSIZE, 512);
curl_exec($curl_handle);

ob_end_clean();
fclose($handle);
Run Code Online (Sandbox Code Playgroud)

好像我总是想念显而易见的事情.正如Marc所指出的那样,CURLOPT_FILE直接将响应写入磁盘.

  • 不需要缓冲.curl可以使用`curl_setopt('CURLOPT_FILE',...)`直接写入文件 (6认同)