How can temporary files be utilized in PHP to optimize file downloads and prevent memory overload?
When downloading large files in PHP, it's important to avoid loading the entire file into memory at once to prevent memory overload. One way to optimize file downloads is by using temporary files. By creating a temporary file, you can write chunks of data to the file as you read them, instead of loading the entire file into memory before sending it to the user for download.
// Set the path for the temporary file
$tempFilePath = tempnam(sys_get_temp_dir(), 'download_');
// Open the temporary file for writing
$tempFile = fopen($tempFilePath, 'w');
// Open the large file for reading
$largeFile = fopen('path/to/large/file', 'r');
// Read and write chunks of data to the temporary file
while (!feof($largeFile)) {
fwrite($tempFile, fread($largeFile, 1024));
}
// Close the file handles
fclose($tempFile);
fclose($largeFile);
// Send the temporary file for download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="downloaded_file.txt"');
readfile($tempFilePath);
// Delete the temporary file
unlink($tempFilePath);