chirag
answered Feb 28 '23 00:00
To force a file download with PHP using the header() function, you need to set the appropriate response headers. Here is an example:
<?php
// Set the content type header
header('Content-Type: application/octet-stream');
// Set the Content-Disposition header to force download
header('Content-Disposition: attachment; filename="example.txt"');
// Read the file contents and output them to the response
readfile('/path/to/example.txt');
?>
In this example, the Content-Type header is set to application/octet-stream , which is a generic binary file type that can be used for any file format. The Content-Disposition header is set to attachment, which instructs the browser to download the file instead of displaying it inline, and specifies the filename of the downloaded file as example.txt.
The readfile() function is then used to read the contents of the file and output them to the response . This causes the file to be downloaded by the browser.