How to force file download with PHP?


The below code can be used to force a file to get downloaded in PHP.

<?php
   header('Content-type: text/javascript');
   header('Content-Disposition: attachment; filename="file.js"');
   readfile(file that is downloaded.js'); //This can be printed for verification purpose
?>

NOTE − This needs to be done before displaying any output, otherwise the file will have output from other operations as well (which might be irrelevant).

Another method that could be used is to use the .htaccess solution. In this method, all the files on the server can be forced to be downloaded, and can be added to the .htaccess file. This has been demonstrated below −

AddType application/octet-stream csv
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=name of csv file');
header('Pragma: no-cache');
readfile("path-to-csv-file");

Updated on: 06-Apr-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements