<?php
class Filetozip {
public $fileName;
public function __construct($filename = NULL) {
if ($filename) {
$this->fileName = $filename;
} else {
$fpath = './ziptmp/' . date('Ymd');
if (!file_exists($fpath)) {
mkdir($fpath, 0777, True);
}
$fname = str_shuffle('ABCDEF') . date('His') . '.zip';
$this->fileName = $fpath . '/' . $fname;
}
}
protected function addDirInFile($zipObj, $dirPath) { //对象直接就是引用传值
$result = opendir($dirPath);
while (($file = readdir($result)) !== False) {
if ('.' != $file && '..' != $file) {
$nowfile = $dirPath . '/' . $file; //注意读出来的是当前目录下的名字,要和主目录连起来成完整的名字才行
if (is_dir($nowfile)) {
$this->addDirInFile($zipObj, $nowfile);
} else {
$zipObj->addFile($nowfile, ltrim($nowfile, '.'));
}
}
}
}
public function addFileCreateZip($file_path) {
$zip = new ZipArchive();
if ($zip->open($this->fileName, ZIPARCHIVE::CREATE) !== TRUE) {
exit('无法打开文件,或者文件创建失败');
}
foreach ($file_path as $v_path) {
if (is_dir($v_path)) {
$this->addDirInFile($zip, $v_path);
} else {
$zip->addFile($v_path, $v_path);
}
}
$zip->close();
}
public function downMe() {
if (!file_exists($this->fileName)) {
exit("无法找到文件"); //即使创建,仍有可能失败。。。。
}
header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-disposition: attachment; filename=' . basename($this->fileName)); //文件名
header("Content-Type: application/zip"); //zip格式的
header("Content-Transfer-Encoding: binary"); //告诉浏览器,这是二进制文件
header('Content-Length: ' . filesize($this->fileName)); //告诉浏览器,文件大小
readfile($this->fileName);
}
}PHP实现文件压缩和下载
作者:jaifire
2017-05-11 17:16
996 阅读