How can PHP headers be utilized to control whether a file is displayed online or automatically downloaded by the user?

To control whether a file is displayed online or automatically downloaded by the user, you can use PHP headers to set the content disposition as inline for displaying the file in the browser or attachment for forcing a download. By setting the content type and content disposition headers, you can control how the browser handles the file.

<?php
// Set the file path
$file = 'path/to/your/file.pdf';

// Set the headers for forcing download
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Length: ' . filesize($file));

// Output the file
readfile($file);
exit;
?>