note 128559 added to class.ziparchive
| From: | theking2 at main dot php dot net | Date: | Sat, 20 May 2023 17:00:33 +0000 |
| Subject: | note 128559 added to class.ziparchive | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-220513@lists.php.net to get a copy of this message | ||
A modern way to zip a folder recursivly is using the DirectoryIterator. I use this little class:
<?php
class MakeZip
{
private ZipArchive $zipArchive;
private int $startPathLength; // chars to remove from the start for the stored entity
public function __construct(
string $zipArchivename,
public readonly string $startPath,
public readonly mixed $convert_function,
)
{
$this->zipArchive = new \ZipArchive;
$this->zipArchive->open($zipArchivename, ZipArchive::CREATE);
$this->startPathLength = strlen($this-> startPath);
$this-> zipDir($startPath);
}
public function __destruct()
{
$this-> zipArchive-> close();
}
/**
* Add files and sub-directories in a folder to zip file.
* @param string $folder
* @param ZipArchive $zipFile
* @param int $exclusiveLength Number of text to be exclusived from the file path.
*/
private function zipDir($folder)
{
echo $folder . '<br>' . PHP_EOL;
foreach (new \DirectoryIterator($folder) as $f) {
if ($f->isDot())
continue; //skip . ..
if ($f->isDir()) {
if( $f->getExtension() === 'git') continue; // skip .git folder
$this-> zipArchive-> addEmptyDir($f->getPathname());
$this-> zipDir($f->getPathname());
continue;
}
if ($f->isFile()) {
if ($f->getBasename() === basename(__FILE__)) continue; // skip self
if ($f->getExtension() === 'zip') continue; // skip ZIP files
$this-> zipArchive ->addFile( substr($f-> getPathname(), $this->
startPathLength) ); // remove './'
continue;
}
}
}
}
?>
Which can be used thusly:
<?php
$host = str_replace('.', '_', $_SERVER['HTTP_HOST']);
$date = date('Ymd-His');
$zip = new \MakeZip("./archiv-$host-$date.zip", './', $convert_function);
unset($zip);
?>
Add encryption or other features in the constructor.
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.13.130 (proxied: 83.97.81.249)
----
Manual Page -- https://php.net/manual/en/class.ziparchive.php
Edit -- https://main.php.net/note/edit/128559
Del: integrated -- https://main.php.net/note/delete/128559/integrated
Del: useless -- https://main.php.net/note/delete/128559/useless
Del: bad code -- https://main.php.net/note/delete/128559/bad+code
Del: spam -- https://main.php.net/note/delete/128559/spam
Del: non-english -- https://main.php.net/note/delete/128559/non-english
Del: in docs -- https://main.php.net/note/delete/128559/in+docs
Del: other reasons-- https://main.php.net/note/delete/128559
Reject -- https://main.php.net/note/reject/128559
Search -- https://main.php.net/manage/user-notes.php