How can PHP be used to force file downloads instead of opening them in the browser?

When a user clicks on a file link in a browser, the default behavior is to open the file in the browser itself. To force a file download instead of opening it in the browser, you can use PHP to send the appropriate headers with the file content. By setting the "Content-Disposition" header to "attachment", you can prompt the browser to download the file instead of displaying it.

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

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
} else {
    echo 'File not found';
}
?>