What are best practices for setting content types and headers when using readfile in PHP for file downloads?
When using readfile in PHP for file downloads, it is important to set the appropriate content type and headers to ensure the file is downloaded correctly. This includes setting the content type to the appropriate MIME type for the file being downloaded and sending headers to specify the file name and content disposition. Failure to set these correctly can result in the file not being downloaded or opened correctly by the user's browser.
$file = 'example.pdf';
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;
Keywords
Related Questions
- What are the potential security risks of using .tpl files for PHP code containing sensitive information like passwords?
- What are some best practices for including external files in PHP, especially when transferring them to a server?
- What are the common challenges faced when saving multiple data rows in a database using PHP?