What are some best practices for handling file downloads in PHP to prevent corruption?
When handling file downloads in PHP, it's important to set the correct headers to prevent corruption. This includes setting the Content-Type header to the appropriate MIME type, Content-Disposition to indicate it's an attachment, and Content-Length to specify the file size. Additionally, using readfile() function to read and output the file content can help prevent corruption.
$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;
Related Questions
- What is the purpose of using sessions in PHP for login functionality?
- What are the best practices for structuring and organizing data in a database-driven information system using PHP?
- What are the potential issues with storing image URLs in a database, especially when it comes to software migration or path changes?