Are there any best practices to follow when sending files for download in PHP to avoid truncation or incomplete downloads?
When sending files for download in PHP, it's important to set the appropriate headers to prevent truncation or incomplete downloads. One common issue is not sending the Content-Length header, which can lead to incomplete downloads. To avoid this, calculate the file size and set the Content-Length header before sending the file contents.
$file = 'path/to/file.ext';
if (file_exists($file)) {
$filesize = filesize($file);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Length: ' . $filesize);
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
readfile($file);
exit;
} else {
echo 'File not found.';
}