What are the best practices for handling large attachments in PHP scripts to avoid memory exhaustion?

Large attachments in PHP scripts can lead to memory exhaustion if the entire file is loaded into memory at once. To avoid this issue, it is recommended to process the attachment in smaller chunks or stream it directly to the output without loading the entire file into memory.

// Set appropriate headers for downloading the attachment
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="large_attachment.zip"');

// Open the attachment file for reading
$attachment = fopen('path/to/large_attachment.zip', 'rb');

// Stream the file to output in smaller chunks
while (!feof($attachment)) {
    echo fread($attachment, 8192); // Read and output 8KB at a time
    ob_flush();
    flush();
}

// Close the file handle
fclose($attachment);