PHP using fwrite and fread with input

I am looking for the most efficient way to write the contents of a PHP input stream to disk without using most of the memory provided by the PHP script. For example, if the maximum file size that can be downloaded is 1 GB, but PHP has only 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);

Does fread inside fwrite, as shown above, mean that the whole file will be loaded into memory?

To do the opposite (write the file to the output stream) PHP offers a function called fpassthru , which, it seems to me, does not contain the contents of the file in the memory of the PHP script.

I am looking for something similar, but vice versa (writing from the input stream to a file). Thanks for any help you can give.

+5
source
1

Yep - fread, , 1 , 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.

+3

All Articles