3

我想从我的网站下载一个 .mp3 文件,但是在使用此代码时,它会在 Firefox 和 Safari 中强制使用 .php。但在 chrome 中,它会强制将文件作为内联发送并在页面上播放。我怎样才能让他们真正下载 .mp3 文件?

$track = $_SERVER['QUERY_STRING'];

if (file_exists("/home/user/gets/" .$track)) {
    header("Content-Type: audio/mpeg");
    header('Content-Length: ' . filesize($track));
    header('Content-Disposition: attachment; filename="test.mp3"');
    $str = "/home/user/gets/".$track;
    readfile($str); 
    exit;
} else {
    header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found', true, 404);
    echo "no file";
}

我也尝试下载 .zip 文件并将 Content-Type 更改为 application/ocetet-stream ,但它会强制所有浏览器上的 .php 文件。

//$track = $_SERVER['QUERY_STRING'];
$track = 'testfile.zip';
if (file_exists("/home/user/gets/" .$track)) {
    header("Content-Type: application/octet-stream");
    header('Content-Length: ' . filesize($track));
    header('Content-Disposition: attachment; filename="test.mp3"');
    $str = "/home/user/gets/".$track;
    readfile($str); 
    exit;
} else {
    header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found', true, 404);
    echo "no file";
}
4

2 回答 2

9

尝试从文件名中去掉引号:

header('Content-Disposition: attachment; filename=test.mp3');
                                                  ^^^^^

获取脚本的名称而不是您尝试使用的文件名通常表明文件名包含浏览器尝试保存到的文件系统的无效字符。例如",不允许。

于 2012-08-16T21:20:48.783 回答
3

I think filesize($track) is wrong, it should be the whole path filesize("/home/user/gets/".$track). This would cause php to output error messages, preventing you from setting the content-length and disposition header.

于 2012-08-16T21:26:25.483 回答