欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php解压缩zip和rar压缩包文件的方法

程序员文章站 2023-11-18 21:40:22
项目涉及文档处理,用户上传的包括 zip 和 rar 压缩包,需要先将压缩包解压后再作处理。对于 zip 压缩包,由于 php 自带 zip 扩展,可以直接解压。 解压z...

项目涉及文档处理,用户上传的包括 zip 和 rar 压缩包,需要先将压缩包解压后再作处理。对于 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() ;

可以看到已经成功安装了 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压缩包文件的方法,希望对大家有所帮助