What are common reasons for the issue of a file being displayed in the browser instead of being downloaded when using PHP for file transfer?
When a file is displayed in the browser instead of being downloaded, it is usually due to the missing or incorrect Content-Disposition header in the PHP code. To force the browser to download the file instead of displaying it, you need to set the Content-Disposition header to "attachment".
<?php
$file = 'example.pdf';
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
readfile($file);
exit;
?>
Keywords
Related Questions
- Is it recommended to store image data in a separate table when working with a large number of text ads in a PHP application?
- What resources or documentation should PHP developers refer to for understanding and implementing MySQL commands effectively in their PHP scripts?
- What is the significance of error reporting in PHP development?