How can PHP be used to offer files for download without displaying them directly in the browser?
To offer files for download without displaying them directly in the browser, you can use PHP to set the correct headers and force the browser to download the file instead of displaying it. This can be achieved by sending the appropriate Content-Type and Content-Disposition headers in the PHP script that serves the file.
<?php
$file = 'path/to/your/file.pdf';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
echo 'File not found';
}
?>
Keywords
Related Questions
- What are the best practices for structuring SQL statements in PHP to retrieve and display data from multiple tables?
- What are the best practices for including PHP files in a website to avoid path problems?
- How can you transfer values from a filtered array using preg_grep into separate variables in PHP?