PHP, Server linux

Chức năng tạo file zip

Chạy trên server linux

Cài module zip cho php

  • sudo apt-get install php-zip

hoặc

  • sudo apt-get install php5.6-zip

Nếu server ko có apt-get thì thay apt-get bằng yum

Restart server
sudo service apache2 restart

hoặc

sudo service httpd restart

 

Code php

 

private function zipFile($diffDir, $zipFile) {
$rootPath = realpath($diffDir);
// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($rootPath), \RecursiveIteratorIterator::LEAVES_ONLY
);
// Initialize archive object
$zip = new \ZipArchive();
$zip->open($zipFile, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
foreach ($files as $name => $file) {
// Skip directories (they would be added automatically)
// if (!$file->isDir()) {
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);

// Add current file to archive
if (!preg_match(‘/\/\.{1,2}$/’, $file)) {
$zip->addFile($filePath, $relativePath);
}
// }
}
// die;
// Zip archive will be created only after closing object
$zip->close();
}