Tags
header
Asked 2 years ago
7 Jul 2021
Views 389
Melba

Melba posted

Force file download with php using header()

Force file download with php using header()
Nilesh

Nilesh
answered Feb 28 '23 00:00

To force file download in php , you should use header() function
Following is the code to download the file in browser in php:

<?php
// We'll be outputting a PDF
header('Content-Type: application/pdf');

// It will be called resume.pdf
header('Content-Disposition: attachment; filename="resume.pdf"');

// The PDF source is in resume.pdf
readfile('resume.pdf');
?>


Explaination :
header('Content-Type: application/pdf');

header() function take a string argument , if you use 'Content-Type: application/pdf' as argument than it send header of pdf download .

header('Content-Disposition: attachment; filename="resume.pdf"');
header() function take a string argument , if you use 'Content-Disposition: attachment; filename="resume.pdf"' as argument than it says that we are sending pdf file as download which have name resume.pdf

after two line of this code you need to send the file content which is done by readfile('resume.pdf');
readfile() is used for read file , and argument is the file path with file name at drive.
chirag

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.

Post Answer