php 下载文件的函数 - carlo-jie
程序员文章站
2023-12-22 22:23:04
...
通过函数完成下载文件的PHP功能代码
function download($url, $filename) {
// 获得文件大小, 防止超过2G的文件, 用sprintf来读
$filesize = sprintf ( "%u", filesize ( $url ) );
if (! $filesize) {
return;
}
header ( "Content-type:application/octet-stream\n" ); //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" . "\n\n" );
} else {
header ( "Content-Length:" . $filesize . "\n\n" );
$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)
推荐阅读
-
php 下载文件的函数 - carlo-jie
-
php 非常有用的高级函数PATH_SEPARATOR常量和set_include_path
-
php stripslashes() 函数删除、过滤字符串中的反斜杠
-
PHP取整函数:ceil,floor,round,intval的区别详细解析_php技巧
-
PHP函数可变参数列表的具体实现方法介绍_PHP教程
-
php生成静态html文件的三种方法
-
详解PHP中的mb_detect_encoding函数使用方法_php技巧
-
jQuery+php实现ajax文件即时上传的详解_php技巧
-
PHP文件读写操作相关函数总结_php技巧
-
php通过ksort()函数给关联数组按照键排序的方法_php技巧