How can PHP handle encoding discrepancies between server and client for file downloads?
When handling file downloads in PHP, encoding discrepancies between the server and client can occur, leading to corrupted files. To ensure proper encoding, you can set the appropriate headers in PHP to specify the content type and encoding of the file being downloaded. This ensures that the file is delivered correctly to the client without any encoding issues.
<?php
$file = 'example.pdf';
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
?>