What are best practices for downloading files in PHP to avoid memory issues?

Downloading large files in PHP can lead to memory issues if the entire file is read into memory before being sent to the client. To avoid this, it's best to read and output the file in chunks rather than all at once. This allows for more efficient memory usage and prevents memory exhaustion when dealing with large files.

$filePath = '/path/to/file.zip';

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');

$handle = fopen($filePath, 'rb');
while (!feof($handle)) {
    echo fread($handle, 8192);
    ob_flush();
    flush();
}
fclose($handle);