PHP下载脚本工作但客户端浏览器不下载

时间:2012-12-01 20:34:37

标签: php download http-headers

此脚本适用于我的http文件服务器。我的文件来自web root,所以我使用php脚本来抓取并将文件发送到客户端。问题是,当我点击文件下载浏览器(ff和chrome)时,我不会问我是否要保存文件。在chrome的网络工具中,在网络下,我看到download.php确实成功执行了。实际上,我甚至可以看到文件在哪里以字节为单位传输请求。但下载的文件不在客户端计算机上。为什么浏览器客户端不询问/下载文件?

Web服务器是Nginx。

<?php

$path = "/trunk/";
$file = $_POST['filename'];
$file_ext = pathinfo($file, PATHINFO_EXTENSION);
$file_name = pathinfo($file, PATHINFO_BASENAME);
$file_full = $path . $file_name;

$finfo = new finfo(FILEINFO_MIME_TYPE);

$ctype = $finfo -> file($file_full);
header("Content-Disposition: attachment; filename=\"".$file_name."\"");
header("Content-Type: " .$ctype);
header("Content-Length: " .filesize($file_full));
error_log(filesize($file_full));

readfile($file_full);

?>

请求标题:

POST /php/download.php HTTP/1.1

    Host: www.example.com
    Connection: keep-alive
    Content-Length: 146
    Origin: https://www.example.com
    User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4
    Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryMA7u5AkYPL9qGmRY
    Accept: */*
    Referer: https://www.example.com/index.php
    Accept-Encoding: gzip,deflate,sdch
    Accept-Language: en-US,en;q=0.8
    Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

响应标题

HTTP/1.1 200 OK
Server: nginx
Date: Sat, 01 Dec 2012 20:22:28 GMT
Content-Type: application/zip
Content-Length: 75090
Connection: keep-alive
Keep-Alive: timeout=300
X-Powered-By: PHP/5.4.6--pl0-gentoo
Content-Disposition: attachment; filename="try.zip"
Expires: Sat, 01 Dec 2012 20:22:27 GMT
Cache-Control: no-cache

1 个答案:

答案 0 :(得分:0)

使用 Content-Type:application / octet-stream 保证在所有浏览器中强制下载。如果您知道要发送二进制内容(如zip),那么也要添加 Content-Transfer-Encoding:binary