What are the best practices for setting headers when offering a file download in PHP?
When offering a file download in PHP, it is important to set the appropriate headers to ensure the file is downloaded correctly by the browser. This includes setting the Content-Type header to specify the file type, Content-Disposition header to prompt the browser to download the file instead of displaying it, and Content-Length header to specify the file size. Additionally, it is recommended to use an appropriate file name in the Content-Disposition header to give the user a meaningful name for the downloaded file.
<?php
// Set headers for file download
$file = 'example.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Length: ' . filesize($file));
// Output the file for download
readfile($file);
exit;
?>
Related Questions
- What potential issues can arise when trying to display and manipulate multiple select box options in PHP?
- What are some common pitfalls when querying a database in PHP, especially when it comes to specifying table and column names?
- What are the best practices for handling user sessions in PHP to ensure accurate online user tracking?