PHP下载文件的函数实例代码

通过函数完成下载文件的PHP功能代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
function download($url, $filename) {
// 获得文件大小, 防止超过2G的文件, 用sprintf来读
$filesize = sprintf ( "%u", filesize ( $url ) );
if (! $filesize) {
return;
}
header ( "Content-type:application/octet-streamn" ); //application/octet-stream
header ( "Content-type:unknown/unknown;" );
header ( "Content-disposition: attachment; filename="" . $filename . """ );
header ( 'Content-transfer-encoding: binary' );
if ($range = getenv ( 'HTTP_RANGE' )) { // 当有偏移量的时候,采用206的断点续传头
$range = explode ( '=', $range );
$range = $range [1];
header ( "HTTP/1.1 206 Partial Content" );
header ( "Date: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s", filemtime ( $url ) ) . " GMT" );
header ( "Accept-Ranges: bytes" );
header ( "Content-Length:" . ($filesize - $range) );
header ( "Content-Range: bytes " . $range . ($filesize - 1) . "/" . $filesize );
header ( "Connection: close" . "nn" );
else {
header ( "Content-Length:" . $filesize . "nn" );
$range = 0; }
loadFile ( $url );}
function loadFile($filename, $retbytes = true) {
$buffer = ''; $cnt = 0; $handle = fopen ( $filename, 'rb' );
if ($handle === false) { return false;
} while ( ! feof ( $handle ) ) {
$buffer = fread ( $handle, 1024 * 1024 );
echo $buffer;
ob_flush ();
flush ();
if ($retbytes) {
$cnt += strlen ( $buffer );
}
}
$status = fclose ( $handle );
if ($retbytes && $status) {
return $cnt; // return num. bytes delivered like readfile() does.
}
return $status;}

输入2个参数即可完成下载 download($url, $filename)

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享
评论 抢沙发

请登录后发表评论