PHP文件下载,PHP本身不会下载文件,实质是通过告诉浏览器要下载文件,要下载的文件在哪?
PHP函数下载
下载一:
header("content-disposition:attachment;filename=$file_name");//告诉浏览器下载文件名称类型
header("content-length:".filesize($file));//文件大小
@readfile($file);//读取文件并写入到输出缓冲
下载二:
header("Content-type:application/octet-stream");
header("Accept-Ranges:bytes");
header("Content-Type:application/force-download");
header("Content-Disposition:inline;filename=".$filename);
header("Accept-Length:".filesize($File));
@readfile($File);//读取文件并写入到输出缓冲
下载三: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; // 返回从文件中读入的字节数,像readfile()。
}
return $status;
}
//输入2个参数即可完成下载
download($url, $filename)
以上就介绍了php 下载文件的函数