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
- How important is it to consult official documentation and community resources when implementing PHP code for sending emails, especially for individuals with limited PHP knowledge?
- What are common pitfalls to avoid when writing a MySQL-based login system in PHP?
- What are some alternative approaches to building and managing dynamic navigation menus in PHP?