标签:php
我已经编写了一个PHP页面,用于从服务器下载文件.文件名作为URL中的GET变量传递,然后以下代码提供文件供下载:
$filepath = "/path/to/files";
$filename = $_GET['id'];
if( ! file_exists($filepath . "/" . $filename) )
{
header("HTTP/1.1 404 Not Found");
@session_destroy();
exit(0);
}
$cmd = '/usr/bin/stat -c "%s" ' . $filepath . "/" . $filename;
$out = array();
$ret = 0;
exec( $cmd, $out, $ret );
header('Content-type: application/octet-stream');
header('Content-Length: ' . $out[0]);
header('Content-Disposition: attachment; filename="' . $filename . '"');
readfile($filepath . "/" . $filename);
注意:我使用exec()调用是因为大多数文件都很大(> 2GB),并且较大的文件导致filesize()和stat()函数失败.
无论如何,此代码几乎可以对几乎所有文件正常工作.但是,当文件的大小恰好为2 GB(2147483648字节)时,不会发送任何标头,浏览器会尝试下载PHP页面本身,这将导致保存一个名为download.php的空文件.
这是我用curl测试的情况:
测试#1:获取一个名为bigfile1的1 GB文件:
$curl -v http:///download.php?id=bigfile1
* About to connect() to port 80 (#0)
* Trying ... connected
* Connected to () port 80 (#0)
> GET /download.php?id=bigfile1 HTTP/1.1
> User-Agent: curl/7.18.2 (i486-pc-linux-gnu) libcurl/7.18.2 OpenSSL/0.9.8g zlib/1.2.3.3 libidn/1.8 libssh2/0.18
> Host:
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Tue, 21 Jun 2011 19:10:06 GMT
< Server: Apache/2.2.4 (Unix) mod_ssl/2.2.4 OpenSSL/0.9.8c PHP/5.3.0
< X-Powered-By: PHP/5.3.0
< Set-Cookie: PHPSESSID=382769731f5e3782e3c1e3e14fc8ae71; path=/
< Expires: Thu, 19 Nov 1981 08:52:00 GMT
< Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
< Pragma: no-cache
< Content-Length: 1073741824
< Content-Disposition: attachment; filename="bigfile1"
< Content-Type: application/octet-stream
<
* Connection #0 to host left intact
* Closing connection #0
测试#2:获取一个名为bigfile2的2 GB文件
$curl -v http:///download.php?id=bigfile2
* About to connect() to port 80 (#0)
* Trying ... connected
* Connected to () port 80 (#0)
> GET /download.php?id=bigfile2 HTTP/1.1
> User-Agent: curl/7.18.2 (i486-pc-linux-gnu) libcurl/7.18.2 OpenSSL/0.9.8g zlib/1.2.3.3 libidn/1.8 libssh2/0.18
> Host:
> Accept: */*
>
* Empty reply from server
* Connection #0 to host left intact
curl: (52) Empty reply from server
* Closing connection #0
我已经创建了大小分别为1 GB,2 GB,3 GB,4 GB和5 GB的测试文件. 2 GB的文件是导致此行为的唯一文件,但它始终发生,并且似乎与客户端浏览器或OS无关.该服务器正在运行Debian GNU / Linux 4.0,Apache 2.2.4和PHP 5.3.0.
任何想法将不胜感激.谢谢!
解决方法:
在64位安装中,使用PHP 5.3.6提到的文件大小没有问题.一个32位安装给了我:
failed to open stream: Value too large for defined data type
但这就是说,我什至不使用readfile.代替:
header("X-Sendfile: $filepath/$filename");
它要求安装和配置mod_xsendfile.
标签:php
来源: https://codeday.me/bug/20191102/1991854.html