PHP 文件操作之打包压缩本地目录为tar.gz包
代码打包目录为tar.gz压缩包(除了下载7-Zip软件之外的另一种方式),主要使用php自有拓展PharData,本来是感兴趣测试一下,还有一点问题是文件名太长报错,应该是addFile函数不支持,最后随便封装了一下
$path = 'C:/Users/Administrator/Desktop/须打包压缩目录';
$obj = new TarGz($path,'default',false,false);
$obj->createTarGz();
随便封装成类,不是很严谨
class TarGz{
protected $files = NULL;
protected $isDown = NULL;
protected $isDel = NULL;
protected $model = NULL;
protected $tar = NULL;
protected $tarGz = NULL;
protected $dirPath = NULL;
protected $path = NULL;
function __construct($path,$model,$isDown,$isDel)
{
$this->path = $path;
$this->dirPath = dirname($path).'/';
$this->isDown = $isDown;
$this->isDel = $isDel;
$this->model = $model=='tree' ? 1:0;
$this->tar = str_replace($this->dirPath,'',$this->path).'.tar';
$this->tarGz = $this->tar.'.gz';
}
protected function searchDir($path,&$files){
if(is_dir($path)){
$opendir = opendir($path);
while ($file = readdir($opendir)){
if($file != '.' && $file != '..') $this->searchDir($path.'/'.$file, $files);
}
closedir($opendir);
}
if(!is_dir($path)) {
if($this->model){
}else{
$files[] = str_replace($this->dirPath,'',$path);
}
}
}
public function createTarGz()
{
$this->searchDir($this->path,$this->files);
$phar = new PharData($this->tar);
$dirs = array();
foreach ($this->files as $f) {
$local = $this->dirPath.$f;
$dir = dirname($local);
$dirs[$dir] = true;
if(!isset($dirs[$dir])) $phar->addEmptyDir($dir);
$phar->addFile($local, $f);
}
$phar->compress(Phar::GZ);
if($this->isDown) $this->DownTarGz($this->tarGz);
if($this->isDel) $this->DelTarGz($this->tarPath, $this->tarGz);
}
public function DownTarGz($tarGz)
{
header("Content-Type: application/x-gzip");
//二进制文件没有特定或已知的subtype,即使用 application/octet-stream,这是应用程序文件的默认值,一般很少直接使用
//header("Content-type:application/octet-stream");
header("Accept-Ranges:bytes");
header("Accept-Length: " . filesize($tarGz));
Header("Content-Disposition:attachment; filename=records.tar.gz");
//读取一个文件,并写入到输出缓冲
//@readfile($tarGz);
}
public function DelTarGz($tar,$tarGz)
{
//临时tar和tar.gz压缩文件,删除重点=权限
@unlink($tar);
@unlink($tarGz);
}
}
空空如也