php解压缩zip和rar压缩包文件

项目涉及文档处理,用户上传的包括ziprar压缩包,需要先将压缩包解压后再作处理。对于zip压缩包,由于php自带zip扩展,可以直接解压。

解压zip压缩包:

$file = "/opt/data/upload/testfile.zip";
$outPath = "/opt/data/upload/testfile";
$zip = new ZipArchive();
$openRes = $zip->open($file);
if ($openRes === TRUE) {
    $zip->extractTo($outPath);
    $zip->close();
}

对于rar压缩包,需要先为php安装rar扩展。

安装rar扩展:

wget http://pecl.php.net/get/rar-4.0.0.tgz
gunzip rar-4.0.0.tgz
tar -xvf rar-4.0.0.tar
cd rar-4.0.0
phpize
./configure && make && make install
# 报错
configure: error: Cannot find php-config. Please use --with-php-config=PATH
# 运行./configure 时指定php-config路径即可
./configure --with-php-config=/usr/local/php/bin/php-config
make && make install

配置rar扩展:

# 新建 /usr/local/php/conf.d/rar.ini,内容
extension=rar.so

重启php-fpm,看一下phpinfo()

php安装rar扩展

可以看到已经成功安装了rar,可以来测试一下解压rar文件。

解压RAR压缩包:

$file = "/opt/data/upload/testfile.zip";
$outPath = "/opt/data/upload/testfile";
$rar_file = rar_open($file);
if ($rar_file) {
    $entries = rar_list($rar_file);
    foreach ($entries as $entry) {
        $entry->extract($outPath);
    }
    rar_close($rar_file);
}

这样就搞定用户上传的压缩包解压的问题了。

php解压缩zip和rar压缩包文件

原文链接:https://beltxman.com/2531.html,若无特殊说明本站内容为 行星带 原创,未经同意禁止转载。

Scroll to top