Tags
Asked 3 years ago
7 Jul 2021
Views 283
Lesly

Lesly posted

How to force a file to download in PHP

How to force a file to download in PHP
debugger

debugger
answered May 1 '23 00:00

you can use the header() function to set the appropriate headers for the download, and then output the contents of the file.

Here is an example code:



$file = "path/to/file.pdf";

// Set headers for download
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));

// Output the contents of the file
readfile($file);
exit;

In this example, the header() function is used to set the following headers:

Content-Description specifies the type of file being downloaded.
Content-Type specifies the MIME type of the file being downloaded.
Content-Disposition specifies the filename of the file being downloaded, and tells the browser to treat it as an attachment.
Expires, Cache-Control, and Pragma are used to ensure that the browser doesn't cache the downloaded file.
Content-Length specifies the size of the file being downloaded.
After setting the headers, the readfile() function is used to output the contents of the file to the browser, and exit is used to stop further execution of the script.
Post Answer