Are there best practices for reading and outputting large files in PHP to prevent memory exhaustion?
Reading and outputting large files in PHP can lead to memory exhaustion if the entire file is loaded into memory at once. To prevent this, it is best to read and output the file line by line or in chunks, rather than loading the entire file into memory.
$filename = 'large_file.txt';
// Open the file for reading
$handle = fopen($filename, 'r');
// Output the file line by line
while (!feof($handle)) {
echo fgets($handle);
}
// Close the file handle
fclose($handle);
Related Questions
- How can Eclipse be configured to use a line feed (\n) instead of a carriage return (\r) when pressing enter?
- What are the potential pitfalls of storing dates as TEXT in a PHP database?
- Are there any specific best practices or guidelines for handling database queries in PHP to avoid errors like "Call to undefined function"?