PHP下载仅适用于包含文本的文件


PHP Download only working for files with text in it

我希望能够使用php从服务器下载文件。到目前为止,它工作得很好,但只适用于包含文本的文件(.txt .php,所以包含简单文本的文件也是如此(即使我有一个有趣的现象,在文本开始之前总是有一行空行……知道为什么吗?),但当我尝试下载.jpg文件或.exe时,它根本不起作用(尝试打开时出错…)

这是我使用的代码:

<?php
session_start();
$file = basename($_GET['file']);
$path = 'uploads/'.$_SESSION['userid']."/".$file;
?>
<?php
if(!file_exists($path)){
    die("file not found");
} else {
    header('Content-Description: File Transfer');
    header('Content-Disposition: attachment; filename="'.$file.'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($path);
    exit;
}

文件中有空行的原因只是因为代码中有空线

...
$path = 'uploads/'.$_SESSION['userid']."/".$file;
?>
                       <--- There's the empty line.
<?php
if(!file_exists($path)){
    die("file not found");
...

解决方案是将两个PHP块合并为一个,而不是两个单独的块。

这也会破坏非文本文件,因为它们实际上会将空行解释为数据并尝试处理它

问题已解决,

我现在更改了我的脚本,以手动对不同类型的文件做出反应,就像这样:

<?php
session_start();
$filename = basename($_GET['file']);
$filename = 'uploads/'.$_SESSION['userid']."/".$filename;
$file_extension = strtolower(substr(strrchr($filename,"."),1));
switch ($file_extension) {
    case "pdf": $ctype="application/pdf"; break;
    case "exe": $ctype="application/octet-stream"; break;
    case "zip": $ctype="application/zip"; break;
    case "doc": $ctype="application/msword"; break;
    case "xls": $ctype="application/vnd.ms-excel"; break;
    case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
    case "gif": $ctype="image/gif"; break;
    case "png": $ctype="image/png"; break;
    case "jpe": case "jpeg":
    case "jpg": $ctype="image/jpg"; break;
    default: $ctype="application/force-download";
}
if (!file_exists($filename)) {
    die("NO FILE HERE");
}
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename='"".basename($filename)."'";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".@filesize($filename));
set_time_limit(0);
@readfile("$filename") or die("File not found.");