【问题标题】:PHP Header Content-Disposition: attachment forces .php file or inlinePHP Header Content-Disposition:附件强制 .php 文件或内联
【发布时间】:2012-08-16 21:16:29
【问题描述】:

我想从我的站点下载一个 .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";
}

【问题讨论】:

  • 我觉得filesize($track)不对,应该是整条路径filesize("/home/user/gets/".$track)

标签: php header download cross-browser mp3


【解决方案1】:

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

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

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

【讨论】:

  • 这也是问题的一部分。谢谢
【解决方案2】:

我觉得filesize($track)错了,应该是整条路径filesize("/home/user/gets/".$track)。这将导致 php 输出错误消息,从而阻止您设置 content-length 和 disposition 标头。

【讨论】:

  • 是的,这是 MarcB 的主要问题。你们俩都是对的。谢谢
猜你喜欢
  • 2016-12-18
  • 1970-01-01
  • 2010-11-26
  • 2017-08-08
相关资源
最近更新 更多