强制使用 PHP 下载文件 [英] Forcing to download a file using PHP
本文介绍了强制使用 PHP 下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的服务器上有一个 CSV 文件.如果用户点击一个链接,它应该下载,但它会在我的浏览器窗口中打开.
I have a CSV file on my server. If a user clicks on a link it should download, but instead it opens up in my browser window.
我的代码如下
<a href="files/csv/example/example.csv">
Click here to download an example of the "CSV" file
</a>
这是一个普通的网络服务器,我的所有开发工作都在其中进行.
It's a normal webserver where I have all of my development work on.
我尝试了类似的东西:
<a href="files/csv/example/csv.php">
Click here to download an example of the "CSV" file
</a>
现在我的 csv.php
文件的内容:
Now the contents of my csv.php
file:
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=example.csv');
header('Pragma: no-cache');
现在我的问题是正在下载,而不是我的 CSV 文件.它会创建一个新文件.
Now my issue is it's downloading, but not my CSV file. It creates a new file.
推荐答案
.htaccess 解决方案
要强制下载服务器上的所有 CSV 文件,请添加您的 .htaccess 文件:
.htaccess Solution
To brute force all CSV files on your server to download, add in your .htaccess file:
AddType application/octet-stream csv
PHP 解决方案
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=example.csv');
header('Pragma: no-cache');
readfile("/path/to/yourfile.csv");
这篇关于强制使用 PHP 下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文