How can PHP scripts be used to generate headers for file downloads with correct content types and filenames?
When serving files for download using PHP, it's important to set the correct headers to ensure the browser interprets the file correctly. This includes setting the Content-Type header to the appropriate MIME type and specifying the filename using the Content-Disposition header. By setting these headers correctly, you can ensure that files are downloaded with the correct content type and filename.
<?php
$file = 'example.pdf';
$filename = 'downloaded_file.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . $filename . '"');
readfile($file);
exit;
?>
Keywords
Related Questions
- How can PHP frameworks like jQuery and AngularJS simplify the process of making AJAX requests in web development?
- How can CSS be utilized to center text in PHP output instead of using deprecated HTML tags like <center>?
- What potential pitfalls should be considered when dealing with XML files with varying values in PHP?