Home >Backend Development >PHP Tutorial >How to force file download using PHP?
The following code can be used to force a file download 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 any output is displayed, otherwise the file will also have output from other operations (which may not be relevant).
Another method that can be used is to use the .htaccess solution. This method can force the download of all files on the server and can be added to the .htaccess file. This is proven 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");
The above is the detailed content of How to force file download using PHP?. For more information, please follow other related articles on the PHP Chinese website!