How to force file download with PHP?

PHPServer Side ProgrammingProgramming

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");
raja
Published on 06-Apr-2020 10:58:37
Advertisements