PHP下载图像和DOCX以外的所有文件已损坏

我已经在一个我一直在做的项目中遇到了严重的问题。

用户将file upload到课程。 上传脚本获取文件名,用下划线replace空格,删除文件扩展名,添加一个4位数字,然后重新添加扩展名。

但是,文件完全上传到服务器(当直接从“上传”文件夹打开,他们没事)。 当下载到用户的计算机时,除DOCX文件和图像外,这些文件全部损坏。

下载的文件打开时,PDF,Excel(xlsx)和powerpoint(pptx)会给出错误消息: “文件已损坏,无法打开”

我必须下载的代码是:

<?php class download extends Controller { public function resource ($filename) { $filepath = realpath('./uploads/resources/courses/' . $filename); header('Content-type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . $filename . '"'); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Pragma: no-cache'); readfile($filepath); } } 

这是一个MVC,所以这就是为什么它在一个类,$文件名是从文件名的$ _GETvariables检索。

任何帮助将非常感激!

看起来像你需要的

 header("Content-Length: " . filesize($filepath)); ob_clean(); flush(); readfile($file); exit; 

请参阅: 如何在PHP中自动启动下载?

另请参阅: 使用phpdocx损坏的.docx下载

您确定下载的文件的文件名中没有空格或其他特殊字符吗? 因为在文件名中有空格或其他特殊字符时会发生这样的问题。