在PHP中将大文件写入磁盘的最佳方式是什么? [英] What is the best way to write a large file to disk in PHP?
问题描述
我有一个PHP脚本,偶尔需要将大文件写入磁盘。使用 file_put_contents()
,如果文件足够大(在这种情况下大约2 MB),PHP脚本内存不足(PHP致命错误:允许的内存大小# ####### bytes exhausted)。我知道我可以增加内存限制,但是这似乎不是一个完整的解决方案,我必须有一个更好的方法,对吗?
<在PHP中写大文件到磁盘的最佳方法是什么? 您需要一个临时文件,在其中放置源文件的位加上要附加的内容:
$ sp = fopen('source' ,'r');
$ op = fopen('tempfile','w');
while(!feof($ sp)){
$ buffer = fread($ sp,512); //使用512字节的缓冲区
fwrite($ op,$ buffer);
}
//追加新数据
fwrite($ op,$ new_data);
//关闭句柄
fclose($ op);
fclose($ sp);
//使临时文件成为新来源
rename('tempfile','source');
这样, source
不被读入内存。使用cURL时,可以省略设置 CURLOPT_RETURNTRANSFER
,而是添加一个写入临时文件的输出缓冲区:
函数write_temp($ buffer){
global $ handle;
fwrite($ handle,$ buffer);
return''; //返回EMPTY字符串,所以没有内部缓冲
$ 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);
好像我总是想念那些显而易见的事物。正如Marc指出的,有 CURLOPT_FILE
可以直接将响应写入磁盘。
I have a PHP script that occasionally needs to write large files to disk. Using file_put_contents()
, if the file is large enough (in this case around 2 MB), the PHP script runs out of memory (PHP Fatal error: Allowed memory size of ######## bytes exhausted). I know I could just increase the memory limit, but that doesn't seem like a full solution to me--there has to be a better way, right?
What is the best way to write a large file to disk in PHP?
You'll need a temporary file in which you put bits of the source file plus what's to be appended:
$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');
That way, the whole contents of source
aren't read into memory. When using cURL, you might omit setting CURLOPT_RETURNTRANSFER
and instead, add an output buffer that writes to a temporary file:
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);
It seems as though I always miss the obvious. As pointed out by Marc, there's CURLOPT_FILE
to directly write the response to disk.
这篇关于在PHP中将大文件写入磁盘的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!