php实现文件下载有许多的方法最多的就是直接显示文件路径了然后点击下载即可,另一种是利用header函数再由filesize与fopen读取文件进行下载了,这个可以实现限速下载了,但是个人认为使用header限速下载大文件是非常的不理想的,下面我们来看个例子.
例子,代码如下:
<?php header( "Content-Type; text/html; charset=utf-8" ); class DownFile { public static function File( $_path , $file_name ) { //解决中文乱码问题 $_path = $_path . $file_name ; //判断文件是否存在 if (! file_exists ( $_path )) { exit ( '文件不存在' ); } $_path =iconv( 'utf-8' , 'gb2312' , $_path ); $file_size = filesize ( $_path ); $fp = fopen ( $_path , 'r' ); header( "Content-type: application/octet-stream" ); header( "Accept-Ranges: bytes" ); header( "Accept-Length: $file_name" ); header( "Content-Disposition: attachment; filename=$file_name" ); $buffer =1024; $file_count =0; while (! feof ( $fp ) && ( $file_size - $file_count >0)) { $file_data = fread ( $fp , $buffer ); $file_count += $buffer ; echo $file_data ; } fclose( $fp ); } } //路径 $path = '' ; //文件名 $file_name = 'filelist.php' ; DownFile::File( $path , $file_name ); ?>分析研究 :使用header函数可以把像服务器端的脚本程序不需打包就可以进行下载了,像如php文件或html文件了,上面例子的核心语句是,代码如下:
$_path =iconv( 'utf-8' , 'gb2312' , $_path ); $file_size = filesize ( $_path ); $fp = fopen ( $_path , 'r' ); header( "Content-type: application/octet-stream" ); header( "Accept-Ranges: bytes" ); header( "Accept-Length: $file_name" ); header( "Content-Disposition: attachment; filename=$file_name" ); $buffer =1024; $file_count =0; while (! feof ( $fp ) && ( $file_size - $file_count >0)) { $file_data = fread ( $fp , $buffer ); $file_count += $buffer ; echo $file_data ; }下面三句,一个转换文件名编码这个防止中文乱码,第一个是获取文件大小,第三个是使用fopen读取文件,代码如下:
$_path =iconv( 'utf-8' , 'gb2312' , $_path ); $file_size = filesize ( $_path ); $fp = fopen ( $_path , 'r' );下面几行代码是告诉浏览器我们要发送的文件是什么内容与文件名,代码如下:
header( "Content-type: application/octet-stream" ); header( "Accept-Ranges: bytes" ); header( "Accept-Length: $file_name" ); header( "Content-Disposition: attachment; filename=$file_name" );下面三行是告诉我们最大下载不能超过1MB第秒,并且循环一直下载,直到文件下载完毕即可,代码如下:
$buffer =1024; $file_count =0; while (! feof ( $fp ) && ( $file_size - $file_count >0)) { $file_data = fread ( $fp , $buffer ); $file_count += $buffer ; echo $file_data ; //开源代码phpfensi.com
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did29424