What are best practices for handling file downloads and displaying images in PHP applications to avoid data corruption or display issues?
When handling file downloads in PHP applications, it is important to set the appropriate headers to ensure the file is downloaded correctly and not corrupted. When displaying images, it is crucial to use the correct content type and encoding to prevent any display issues.
// File Download
$file = 'path/to/file.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);
// Display Image
$image = 'path/to/image.jpg';
header('Content-Type: image/jpeg');
readfile($image);