How to stream large files for download in PHP without consuming too much memory?

To stream large files for download in PHP without consuming too much memory, you can use the following approach:

  1. Start by opening the file using fopen() function with the file path and "rb" mode:
$file = fopen($filePath, "rb");
  1. Set the appropriate headers to ensure the file is downloaded and not displayed in the browser:
header("Content-Type: application/octet-stream"); header("Content-Transfer-Encoding: Binary"); header("Content-Disposition: attachment; filename=\"" . basename($filePath) . "\"");
  1. Determine the file size and set the Content-Length header to allow the browser to display the download progress:
header("Content-Length: " . filesize($filePath));
  1. Flush any output buffers and disable output buffering to prevent memory exhaustion:
while (ob_get_level()) { ob_end_clean(); }
  1. Read and output the file content in chunks, rather than loading the entire file into memory at once:
while (!feof($file)) { print(fread($file, 1024 * 8)); // Adjust the chunk size as needed flush(); }
  1. Finally, close the file handle:
fclose($file);

This approach allows PHP to read and output the file in smaller chunks, reducing memory consumption and allowing larger files to be streamed without issues.