What potential pitfalls should be considered when manipulating content types in PHP for file downloads?
When manipulating content types in PHP for file downloads, one potential pitfall to consider is ensuring that the content type matches the actual file being downloaded. This is important for security reasons as misrepresenting the content type can lead to vulnerabilities such as content sniffing attacks. It is also important to properly handle file extensions and sanitize user input to prevent any malicious files from being downloaded.
// Set the correct content type based on the file extension
$file = 'example.pdf';
$mime_types = array(
'pdf' => 'application/pdf',
'doc' => 'application/msword',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
// Add more file types as needed
);
$extension = pathinfo($file, PATHINFO_EXTENSION);
$content_type = isset($mime_types[$extension]) ? $mime_types[$extension] : 'application/octet-stream';
header("Content-Type: $content_type");
header("Content-Disposition: attachment; filename=\"$file\"");
readfile($file);
Keywords
Related Questions
- What is the significance of using single quotes in array keys in PHP and how can it affect data retrieval?
- What improvements can be made to the PHP script to enhance readability and maintainability, considering the current structure and logic?
- How can a user be greeted on a website after successfully logging into a PHP forum?