php实现对文件压缩简单的方法

2025-05-27 0 34

压缩一个文件

我们将一个文件生成一个压缩包。

?

1

2

3

4

5

6

7

8

9

10

11

12

13
<?php

$path = "c:/wamp/www/log.txt";

$filename = "test.zip";

$zip = new ZipArchive();

$zip->open($filename,ZipArchive::CREATE); //打开压缩包

$zip->addFile($path,basename($path)); //向压缩包中添加文件

$zip->close(); //关闭压缩包

上述代码将c:/wamp/www/log.txt文件压缩生成了test.zip,并保存在当前目录。

压缩多个文件

压缩多个文件,其实就是addFile执行多次,可以通过数组的遍历来实现。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23
<?php

$fileList = array(

"c:/wamp/www/log.txt",

"c:/wamp/www/weixin.class.php"

);

$filename = "test.zip";

$zip = new ZipArchive();

$zip->open($filename,ZipArchive::CREATE); //打开压缩包

foreach($fileList as $file){

$zip->addFile($file,basename($file)); //向压缩包中添加文件

}

$zip->close(); //关闭压缩包

压缩一个目录

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37
<?php

function addFileToZip($path,$zip){

$handler=opendir($path); //打开当前文件夹由$path指定。

while(($filename=readdir($handler))!==false){

if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..',不要对他们进行操作

if(is_dir($path."/".$filename)){// 如果读取的某个对象是文件夹,则递归

addFileToZip($path."/".$filename, $zip);

}else{ //将文件加入zip对象

$zip->addFile($path."/".$filename);

}

}

}

@closedir($path);

}

$zip=new ZipArchive();

if($zip->open('rsa.zip', ZipArchive::OVERWRITE)=== TRUE){

addFileToZip('rsa/', $zip); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法

$zip->close(); //关闭处理的zip文件

}

压缩并下载zip包

我的时候,我们需要打包之后,提供下载,然后删除压缩包。

可以分为以下几步:

(1)判断给出的路径,是文件夹,还是文件。文件夹还需要遍历添加文件。

(2)设置相关文件头,并使用readfile函数提供下载。

(3)使用unlink函数删除压缩包。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55
<?php

function addFileToZip($path,$zip){

$handler=opendir($path); //打开当前文件夹由$path指定。

while(($filename=readdir($handler))!==false){

if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..',不要对他们进行操作

if(is_dir($path."/".$filename)){// 如果读取的某个对象是文件夹,则递归

addFileToZip($path."/".$filename, $zip);

}else{ //将文件加入zip对象

$zip->addFile($path."/".$filename);

}

}

}

@closedir($path);

}

$zip=new ZipArchive();

if($zip->open('rsa.zip', ZipArchive::OVERWRITE)=== TRUE){

$path = 'rsa/';

if(is_dir($path)){ //给出文件夹,打包文件夹

addFileToZip($path, $zip);

}else if(is_array($path)){ //以数组形式给出文件路径

foreach($path as $file){

$zip->addFile($file);

}

}else{ //只给出一个文件

$zip->addFile($path);

}

$zip->close(); //关闭处理的zip文件

}

以上就是php如何实现对文件压缩的详细内容,感谢大家的学习和对快网idc的支持。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 php实现对文件压缩简单的方法 https://www.kuaiidc.com/71265.html

相关文章

发表评论
暂无评论