What are the advantages of directly offering a file for download in PHP instead of saving it on the server first?
When directly offering a file for download in PHP instead of saving it on the server first, it saves server storage space and reduces the processing time required to handle the file. This method also provides a more efficient way to deliver files to users without the need to store them permanently on the server.
<?php
$file = 'path/to/file.pdf';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
echo 'File not found.';
}
?>