How to force to download a file using PHP?

Spread the love

Sometimes, we want to force to download a file using PHP.

In this article, we’ll look at how to force to download a file using PHP.

How to force to download a file using PHP?

To force to download a file using PHP, we can set a few headers.

For instance, we write

header("Content-Type: application/csv");
header("Content-Disposition: attachment; filename=example.csv");
header("Pragma: no-cache");
readfile("/path/to/yourfile.csv");

to call header with "Content-Disposition: attachment; filename=example.csv" to set the Content-Disposition header to attachment so that the file is downloaded.

The file name of the downloaded file is example.csv.

Then we call readfile to read the file and it’ll be downloaded in the browser because of the header.

Conclusion

To force to download a file using PHP, we can set a few headers.

Leave a Reply

Your email address will not be published.