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

编程学习 2021-07-05 09:10www.dzhlxh.cn编程入门
本文通过实例代码给大家介绍php下载文件的函数相关知识,介绍的非常详解,具有参考借鉴价值,感兴趣的朋友一起学习吧

通过函数完成下载文件的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下载文件的函数实例代码的相关知识,希望对大家有所帮助,如果大家有任何疑问请给我留言,长沙网络推广会及时回复大家的。在此也非常感谢大家对狼蚁SEO网站的支持!

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板