概述
在很多实际生产场景都需要批量上传、下载一些文件的处理,整理了使用php语言操作ziparchive实践和实例,ziparchive需要服务器上安装zlib库,php扩展中安装zip扩展。
服务器环境扩展
ziparchive类库的php版本要求如下,另外php需要查看是否已经成功安装zip扩展,服务器上需要安装zlib包,具体查看方法在下面的代码段里。
# ziparchive 类版本要求,来自官网 # (php 5 >= 5.2.0, php 7, php 8, pecl zip >= 1.1.0) #查看是否安装zlib包 yum list installed | grep zlib php-fpm -m | grep zip zip $zipversion = phpversion('zip'); echo "zip extension version: " . $zipversion.php_eol; # 输出结果 # zip extension version: 1.15.6
实践
ziparchive类,使用范围非常丰富,这篇博客里主要介绍上传和下载功能,先整理下载的实践实例,有几点需要特别注意的点:
- 目录和文件的权限,包括复制的源文件和目标文件
- 移动的文件夹一定要存在
- ziparchive扩展所需要的zlib和zip扩展,注意版本的差异性
文件下载
文件下载相对比较容易,先创建一个空的zip包,在把需要压缩的文件添加进zip包里。
//压缩包生成的路径,最后文件添加在这个zip包中 $destination = '/home/wwwroot/testdemo.zip'; if (!file_exists(dirname($destination))) { mkdir(dirname($destination), 0777, true); } $zip = new ziparchive; if ($zip->open($destination, ziparchive::create) !== true) { echo '服务器错误'.php_eol; } $filepath = '/server_images/data/劳务派遣协议.pdf'; $filesuffix = pathinfo($filepath,pathinfo_extension); // 输出 pdf $filename = pathinfo($filepath, pathinfo_filename); // 输出 劳务派遣协议 $rename = 'stark_' . $filename.'.'.$filesuffix; //新名字 #把路径$filepath 生成到zip包中,$rename是新的文件名 $zip->addfile($filepath, $rename ); # 创建目录的路径 $createpathname = ''; $zip->addemptydir($createpathname); $zip->close(); $strfile = '劳务派遣协议.zip'; header("content-type:application/zip"); header("content-disposition:attachment;filename=" . $strfile); readfile($destination);
文件上传
1、文件上传相对比较麻烦,首先要把文件移动到指定的目录下,demo中的例子是$file_path
$file_path = '/home/wwwroot/upload/'; if (!is_dir(dirname($file_path))) { mkdir(dirname($file_path), 0777, true); } //把文件移动到$file_path目录里 if( is_uploaded_file($_files['file']['tmp_name']) ) { $move_re = move_uploaded_file($_files['file']['tmp_name'], $file_path); if (!$move_re) { echo '上传失败'.php_eol; } }else{ echo '请检查数据来源'.php_eol; }
2、对压缩包进行解压
$destination = '/home/wwwroot/labor_con2.zip'; $zip = new ziparchive; if ($zip->open($destination, ziparchive::create) !== true) { echo '服务器错误'.php_eol; } //解压到目标目录 $extractdir $extractdir = '/home/wwwroot/zip'; if (!is_dir($extractdir)) { mkdir($extractdir, 0777, true); } $zip->extractto($extractdir); $zip->close();
3、把解压的文件移动到目标的资源文件夹里
$zipname = 'labor_con2'; $realextractdir = $extractdir.'/'.$zipname.'/'; $folders = scandir($realextractdir); //把$extracttopath 移动到 $targetsrc位置 $targetdir = '/server_images/data/target/'; if (!is_dir($targetdir)) { mkdir($targetdir, 0777, true); } foreach ( $folders as $file){ if(!in_array($file,['.','..','.ds_store'])){ $sourcesrc = $realextractdir.$file; $targetsrc = $targetdir.$file; if (file_exists($sourcesrc)) chmod($sourcesrc, 0755); if (file_exists($targetsrc)) chmod($targetsrc, 0755); $result = copy($sourcesrc, $targetsrc); if($result){ echo '文件复制成功了'.php_eol; } } }
到此这篇关于php操作ziparchive实现文件上传下载功能的文章就介绍到这了,更多相关php ziparchive文件上传下载内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论