What are some alternative methods to sending large files like MP3s in PHP to avoid memory exhaustion?

When sending large files like MP3s in PHP, memory exhaustion can occur if the entire file is loaded into memory before being sent. To avoid this issue, you can use alternative methods such as streaming the file directly to the output buffer without loading it entirely into memory.

// Set appropriate headers for file download
header('Content-Type: audio/mpeg');
header('Content-Disposition: attachment; filename="example.mp3"');

// Open the file for reading
$filePath = 'path/to/example.mp3';
$handle = fopen($filePath, 'rb');

// Stream the file to the output buffer in chunks
while (!feof($handle)) {
    echo fread($handle, 8192); // Adjust chunk size as needed
    ob_flush();
    flush();
}

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