Home  >  Article  >  Backend Development  >  How to force file download using PHP?

How to force file download using PHP?

WBOY
WBOYforward
2023-09-05 08:49:041364browse

How to force file download using PHP?

The following code can be used to force a file download in PHP.

<?php
   header(&#39;Content-type: text/javascript&#39;);
   header(&#39;Content-Disposition: attachment; filename="file.js"&#39;);
   readfile(file that is downloaded.js&#39;); //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(&#39;Content-Type: application/csv&#39;);
header(&#39;Content-Disposition: attachment; filename=name of csv file&#39;);
header(&#39;Pragma: no-cache&#39;);
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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete