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;
?>
Related Questions
- Are there any existing solutions or tools that can automate the process of updating PHP scripts and files across multiple servers?
- What potential pitfalls should be considered when using PHP to validate form submissions?
- What are the best practices for error handling in PHP when using mysqli functions?