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);
Related Questions
- What are common pitfalls when using str_replace in PHP, especially when working with arrays of variables?
- How can AJAX or jQuery be utilized in PHP to improve the user experience in a seat reservation application?
- How can one improve code readability and security in PHP by utilizing PDO instead of string concatenation for database operations?