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;
?>