Skip to content
PHP Logo

What is the potential issue with writing very large files in PHP?

Writing very large files in PHP can potentially lead to memory exhaustion due to the entire file being loaded into memory before being written. To solve this issue, it is recommended to write the file in smaller chunks or use stream-based writing to avoid loading the entire file into memory at once.

php
$sourceFile = 'large_file.txt';
$destinationFile = 'output_file.txt';

$sourceHandle = fopen($sourceFile, 'r');
$destinationHandle = fopen($destinationFile, 'w');

while (!feof($sourceHandle)) {
    $chunk = fread($sourceHandle, 8192); // Read 8KB at a time
    fwrite($destinationHandle, $chunk);
}

fclose($sourceHandle);
fclose($destinationHandle);