How can headers be used in PHP to indicate to the client that a file transfer is taking place?
To indicate to the client that a file transfer is taking place in PHP, headers can be used to send appropriate HTTP headers before sending the file contents. This includes setting the Content-Type header to the appropriate MIME type for the file being transferred and using the Content-Disposition header to specify the filename for the client to save the file as.
<?php
$file = 'example.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
?>
Related Questions
- What are the best practices for storing and accessing session variables in PHP?
- How can a PHP developer ensure that database entries are only made once per login session?
- How can PHP developers effectively transition from using mysql_ extension to PDO or mysqli for improved compatibility and security?