How can PHP developers prevent the display of garbled characters when initiating file downloads?
To prevent the display of garbled characters when initiating file downloads in PHP, developers can set the appropriate headers to specify the content type as application/octet-stream and force the browser to download the file instead of trying to display it.
<?php
$file = 'example.pdf';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
?>
Related Questions
- What are the potential benefits of uploading files to a server using FTP instead of PHP?
- How can the code snippet be optimized to improve performance when processing and displaying sorted data from a MySQL database in PHP?
- How can proper indentation and structuring improve the readability and maintainability of PHP code?