php - 强制文件下载代码在本地主机上工作,但在 php 中的实际服务器上不工作

我是初学者的 php 程序员。我已经编写代码来下载任何类型的文件。

当我点击下载链接时,它会转到 download.php 文件。我在本地服务器上工作,但不在服务器上工作。

我的代码是:

header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');    //application/force-download
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        //header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
        exit();

是我的代码有误还是服务器需要一些设置?

最佳答案

这是在线测试的代码,它工作正常。你可以试试这个

$folder_name = $_GET['fol_name'];
$file_directory = "../img/files/$folder_name"; //Name of the directory where all the sub directories and files exists

$file = $_GET['file_name']; //Get the file from URL variable

$file_array = explode('/', $file); //Try to seperate the folders and filename from the path
$file_array_count = count($file_array); //Count the result
$filename = $file_array[$file_array_count-1]; //Trace the filename
$file_path = dirname(__FILE__).'/'.$file_directory.'/'.$file; //Set the file path w.r.t the download.php... It may be different for u

if(file_exists($file_path)) {
    header("Content-disposition: attachment; filename={$filename}"); //Tell the filename to the browser
    header('Content-type: application/octet-stream'); //Stream as a binary file! So it would force browser to download
    readfile($file_path); //Read and stream the file
}
else {
    echo "Sorry, the file does not exist!";
}

谢谢你!!

https://stackoverflow.com/questions/17289928/

相关文章:

r - 使用包命名空间在 R 中进行分层 cox 回归

sql-server - 在 SQL Server 中的数字字段上没有聚合的数据透视

ruby-on-rails - 如何加入 Rails 中的多对多表

css - 在相同高度缩放 float div

python - 如何在对象上进行 str.replace?

xaml - Telerik RadMaskedNumericInput 掩码

python - MindWave Mobile - 调用单个数据点

sql-server - 对选择结果中的每一行执行 INSERT

ms-access - 如何在 vba(access) 中将变量设置为我的表单列表框之一?

javascript - Xhr 上传事件.loaded 问题