PHP解压ZIP与RAR文件的方法对比
处理ZIP文件时,可参考PclZip库,其官方地址为 http://www.phpconcept.net/pclzip/index.en.php
处理RAR文件时,可使用PECL rar扩展,包地址为 http://pecl.php.net/package/rar
过去在PHP中执行解压缩程序,最常见的方法是编写命令行指令,然后通过exec()等函数来运行
这种方法在Windows系统中或许可行,但切换到Unix环境时,往往会因账户权限问题导致无法顺利执行
那么,是否存在一种无需下达command命令,而是直接提供函数供调用的方法呢?
答案是肯定的(笔者为此寻找了数日才找到可用的方案......XD)
先说ZIP,虽然PHP内置了zip相关函数(前提是必须启用ziplib扩展),但其易用性欠佳
仅以extract为例,内置函数仅负责将档案单纯解压出来,而不会按照文件夹层级顺序进行解压
这会导致extract功能失去原本的意义
而推荐的PclZip库本身已包含扩展代码,因此是否拥有Ziplib并不影响使用
且该库免安装,使用时只需将其include进来即可
例如:
<?php include('pclzip.lib.php'); ?>这样引入后即可使用
此外在extract部分,它会按照资料夹顺序依序解压缩出来,而并非单纯解压缩档桉出来
相关用法像这样
<?php require_once('pclzip.lib.php');
$archive = new PclZip('archive.zip');
if ($archive->extract() == 0) { /*解压缩路径跟原始档相同路径*/
die("Error : ".$archive->errorInfo(true));
}
?> 当然也可以指定解压缩路径,像这样
<?php include('pclzip.lib.php');
$archive = new PclZip('archive.zip');
if ($archive->extract(PCLZIP_OPT_PATH, 'data') { /*data换成其他路径即可*/
die("Error : ".$archive->errorInfo(true));
}
?> 如果再写一支自动建立目录的script会更好,因为函式本身不会判断压缩档裡第一层是档桉还是资料夹(这我想其他相关函式也做不到吧!!!)
再来是Rar,这问题比较大,由于php本身没提供rar相关函式,所以需要求助第三方函式来用
所幸有这个 PECL(The PHP Extension Community Library)
裡面有个 rar 的 package 可以使用
不过须得手动安装才行
若是 Unix 话,可以参考下列安装法
fetch http://pecl.php.net/get/rar-x.x.x.tgz
gunzip rar-xxx.tgz
tar -xvf rar-xxx.tar
cd rar-xxx
phpize
./configure && make && make install
当然若是 freebsd 话,用 port 装会更快
cd /usr/ports/archivers/pecl-rar
make
make install
记得安装完后须 restart apache
安装完后可以做测试
<?php $rar_file = rar_open('example.rar') or die("Failed to open Rar archive");
/*example.rar换成其他档桉即可*/
$entries_list = rar_list($rar_file);
print_r($entries_list);
?> 比较要注意的,若是用 port 安装话,版本会比较新(官网只有到0.3.1,port 安装话已经到0.3.4),所以用法上会有些出入
但extract用法上并无差异
相关用法像这样
<?php $rar_file = rar_open('example.rar') or die("Can't open Rar archive");
/*example.rar换成其他档桉即可*/
$entries = rar_list($rar_file);
foreach ($entries as $entry) {
$entry->extract('/dir/extract/to/'); /*/dir/extract/to/换成其他路径即可*/
} rar_close($rar_file);
?> 跟Zip部分一样,若搭配自动建立目录会更好