How to force file download using PHP?

WBOY
Release: 2023-09-05 09:08:02
forward
1347 people have browsed it

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
?>
Copy after login

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");
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!