如何使用 PHP 强制下载文件?
phpserver side programmingprogramming更新于 2025/4/18 0:07:17
以下代码可用于在 PHP 中强制下载文件。
<?php
header('Content-type: text/javascript');
header('Content-Disposition: attachment; filename="file.js"');
readfile(file that is downloaded.js'); //这可以打印出来用于验证目的
?>
注意 −这需要在显示任何输出之前完成,否则文件也会有其他操作的输出(可能无关紧要)。
可以使用的另一种方法是使用 .htaccess 解决方案。在此方法中,可以强制下载服务器上的所有文件,并将其添加到 .htaccess 文件中。这已在下面演示 −
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");

