What are the best practices for handling file downloads in PHP scripts?
When handling file downloads in PHP scripts, it is important to set the appropriate headers to ensure the file is downloaded correctly. This includes setting the content type, content disposition, and content length headers. Additionally, it is recommended to use readfile() function to output the file contents.
<?php
$file = 'example.pdf';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
echo 'File not found.';
}
?>
Related questions
-
security implications redirecting users PHP scripts
-
PHP code structuring design options
-
strpos str_replace highlight search terms