程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> php 下載文件的函數,

php 下載文件的函數,

編輯:關於PHP編程

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)

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved