What is the best way to write a large file to disk in PHP? -


i have php script needs write large files disk. using file_put_contents(), if file large enough (in case around 2 mb), php script runs out of memory (php fatal error: allowed memory size of ######## bytes exhausted). know increase memory limit, doesn't seem full solution me--there has better way, right?

what best way write large file disk in php?

you'll need temporary file in put bits of source file plus what's appended:

$sp = fopen('source', 'r'); $op = fopen('tempfile', 'w');  while (!feof($sp)) {    $buffer = fread($sp, 512);  // use buffer of 512 bytes    fwrite($op, $buffer); }  // append new data fwrite($op, $new_data);      // close handles fclose($op); fclose($sp);  // make temporary file new source rename('tempfile', 'source'); 

that way, whole contents of source aren't read memory. when using curl, might omit setting curlopt_returntransfer , instead, add output buffer writes temporary file:

function write_temp($buffer) {      global $handle;      fwrite($handle, $buffer);      return '';   // return empty string, 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 though miss obvious. pointed out marc, there's curlopt_file directly write response disk.


Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -