手机浏览 RSS 2.0 订阅 膘叔的简单人生 , 腾讯云RDS购买 | 超便宜的Vultr , 注册 | 登陆

几行代码实现文件打包下载

首页 > PHP >

短短几行代码实现文件打包下载。。。

PHP代码
  1. /** 
  2.  * 没有写成class 或者 function ,需要的朋友自己写,就这么几行。。 
  3.  */  
  4. $filename = "./test/test.zip"//最终生成的文件名(含路径)  
  5. if(!file_exists($filename)){  
  6.     //重新生成文件  
  7.     $zip = new ZipArchive();//使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释  
  8.     if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) {  
  9.         exit('无法打开文件,或者文件创建失败');  
  10.     }  
  11.     foreach$datalist as $val){  
  12.         $attachfile = $attachmentDir . $val['filepath'];    //获取原始文件路径  
  13.         if(file_exists($attachfile)){  
  14.             $zip->addFile( $attachfile , basename($attachfile));//第二个参数是放在压缩包中的文件名称,如果文件可能会有重复,就需要注意一下  
  15.         }  
  16.     }  
  17.     $zip->close();//关闭  
  18. }  
  19. if( !file_exists($filename)){  
  20.     exit("无法找到文件"); //即使创建,仍有可能失败。。。。  
  21. }  
  22. header("Cache-Control: public");   
  23. header("Content-Description: File Transfer");   
  24. header('Content-disposition: attachment; filename='.basename($filename)); //文件名  
  25. header("Content-Type: application/zip"); //zip格式的  
  26. header("Content-Transfer-Encoding: binary");    //告诉浏览器,这是二进制文件   
  27. header('Content-Length: 'filesize($filename));    //告诉浏览器,文件大小  
  28. @readfile($filename);         




本站采用创作共享版权协议, 要求署名、非商业和保持一致. 本站欢迎任何非商业应用的转载, 但须注明出自"易栈网-膘叔", 保留原始链接, 此外还必须标注原文标题和链接.

Tags: php, 文件下载, zip压缩

« 上一篇 | 下一篇 »

只显示10条记录相关文章

使用PHP得到所有的HTTP请求头 (浏览: 62818, 评论: 3)
我为什么会选用phpstorm (浏览: 52740, 评论: 5)
快速生成目录树 (浏览: 46882, 评论: 7)
通过file_get_contents来Post数据的实例 (浏览: 46445, 评论: 5)
PHP导入导出Excel方法 (浏览: 45267, 评论: 3)
PHP的XSS攻击过滤函数 (浏览: 42761, 评论: 2)
PHP中Eval的作用 (浏览: 41713, 评论: 4)
超详细:在Mac OS X中配置Apache + PHP + MySQL (浏览: 40435, 评论: 1)
PHP常见错误(二) (浏览: 39834, 评论: 1)
PHP sendmail (浏览: 38018, 评论: 7)

1条记录访客评论

wwww

Post by wwww on 2012, January 20, 10:13 AM 引用此文发表评论 #1


发表评论

评论内容 (必填):