php 强制下载zip,php 如何打包下载ziparchive的使用

之前在做一个有关文件操作的时候,遇到一个多文件下载的问题

//php 打包

/* creates a compressed zip file */

function create_zip($files = array(),$destination = '',$overwrite = false) {

//if the zip file already exists and overwrite is false, return false

if(file_exists($destination) && !$overwrite) { return false; }

//vars

$valid_files = array();

//if files were passed in...

if(is_array($files)) {

//cycle through each file

foreach($files as $file) {

//make sure the file exists

if(file_exists($file)) {

$valid_files[] = $file;

}

}

}

//if we have good files...

if(count($valid_files)) {

//create the archive php 系统自带类,具体使用方法参照:http://cn2.php.net/manual/en/class.ziparchive.php

$zip = new ZipArchive();

if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {

return false;

}

//add the files

foreach($valid_files as $file) {

$zip->addFile($file,$file);

}

//debug

//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;

//close the zip -- done!

$zip->close();

//check to make sure the file exists

return file_exists($destination);

}

else

{

return false;

}

}

//Sample Usage

$files_to_zip = array(

'preload-images/1.jpg',

'preload-images/2.jpg',

'preload-images/5.jpg',

'kwicks/ringo.gif',

'rod.jpg',

'reddit.gif'

);

//if true, good; if false, zip creation failed

$result = create_zip($files_to_zip,'my-archive.zip');

// php下载

function download($file_dir='web/uploadfile/', $file_name)

{

//检查文件是否存在

if (! file_exists ( $file_dir . $file_name )) {

echo "文件找不到";

exit ();

} else {

//打开文件

$file = fopen ( $file_dir . $file_name, "r" );

//输入文件标签

Header ( "Content-type: application/octet-stream" );

Header ( "Accept-Ranges: bytes" );

Header ( "Accept-Length: " . filesize ( $file_dir . $file_name ) );

Header ( "Content-Disposition: attachment; filename=" . $file_name );

//输出文件内容

//读取文件内容并直接输出到浏览器

echo fread ( $file, filesize ( $file_dir . $file_name ) );

fclose ( $file );

exit ();

}

}

转载时请注明出处及相应链接,本文永久地址:https://blog.yayuanzi.com/2342.html

75d087ef9a9fb11dc373caaf33adbf7f.png

微信打赏

支付宝打赏

感谢您对作者surfin的打赏,我们会更加努力!    如果您想成为作者,请点我

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值