PHP Doku:: Fügt ein neues Verzeichnis hinzu - function.ziparchive-addemptydir.html

Verlauf / Chronik / History: (50) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzErweiterungen zur Datenkompression und ArchivierungZipThe ZipArchive classZipArchive::addEmptyDir

Ein Service von Reinhard Neidl - Webprogrammierung.

The ZipArchive class

<<The ZipArchive class

ZipArchive::addFile>>

ZipArchive::addEmptyDir

(PHP 5 >= 5.2.0, PECL zip >= 1.8.0)

ZipArchive::addEmptyDirFügt ein neues Verzeichnis hinzu

Beschreibung

bool ZipArchive::addEmptyDir ( string $dirname )

Fügt dem Archiv ein neues Verzeichnis hinzu.

Parameter-Liste

dirname

Das hinzuzufügende Verzeichnis.

Rückgabewerte

Gibt bei Erfolg TRUE zurück. Im Fehlerfall wird FALSE zurückgegeben.

Beispiele

Beispiel #1 Erstellt ein neues Verzeichnis im Archiv

<?php
$zip 
= new ZipArchive;
if (
$zip->open('test.zip') === TRUE) {
    if(
$zip->addEmptyDir('newDirectory')) {
        echo 
'Neues Rootverzeichnis erstellt.';
    } else {
        echo 
'Konnte Verzeichnis nicht erstellen.';
    }
    
$zip->close();
} else {
    echo 
'Fehler';
}
?>

7 BenutzerBeiträge:
- Beiträge aktualisieren...
hunter666 at abv dot bg
26.06.2010 22:44
Add folder and sub-directories to zip archive.

<?php
$archive_name
= "archive.zip"; // name of zip file
$archive_folder = "folder"; // the folder which you archivate

$zip = new ZipArchive;
if (
$zip -> open($archive_name, ZipArchive::CREATE) === TRUE)
{
   
$dir = preg_replace('/[\/]{2,}/', '/', $archive_folder."/");
   
   
$dirs = array($dir);
    while (
count($dirs))
    {
       
$dir = current($dirs);
       
$zip -> addEmptyDir($dir);
       
       
$dh = opendir($dir);
        while(
$file = readdir($dh))
        {
            if (
$file != '.' && $file != '..')
            {
                if (
is_file($file))
                   
$zip -> addFile($dir.$file, $dir.$file);
                elseif (
is_dir($file))
                   
$dirs[] = $dir.$file."/";
            }
        }
       
closedir($dh);
       
array_shift($dirs);
    }
   
   
$zip -> close();
    echo
'Archiving is sucessful!';
}
else
{
    echo
'Error, can\'t create a zip file!';
}
?>
thomas dot rubbert at yahoo dot de
31.05.2009 2:19
Here's a stack-based way to zip a directory. No recursion, no function, no class:

<?php
$zip
= new ZipArchive();
$zip->open('test.zip', ZipArchive::CREATE);

$dirName = 'test';

if (!
is_dir($dirName)) {
    throw new
Exception('Directory ' . $dirName . ' does not exist');
}

$dirName = realpath($dirName);
if (
substr($dirName, -1) != '/') {
   
$dirName.= '/';
}

/*
 * NOTE BY danbrown AT php DOT net: A good method of making
 * portable code in this case would be usage of the PHP constant
 * DIRECTORY_SEPARATOR in place of the '/' (forward slash) above.
 */

$dirStack = array($dirName);
//Find the index where the last dir starts
$cutFrom = strrpos(substr($dirName, 0, -1), '/')+1;

while (!empty(
$dirStack)) {
   
$currentDir = array_pop($dirStack);
   
$filesToAdd = array();

   
$dir = dir($currentDir);
    while (
false !== ($node = $dir->read())) {
        if ((
$node == '..') || ($node == '.')) {
            continue;
        }
        if (
is_dir($currentDir . $node)) {
           
array_push($dirStack, $currentDir . $node . '/');
        }
        if (
is_file($currentDir . $node)) {
           
$filesToAdd[] = $node;
        }
    }

   
$localDir = substr($currentDir, $cutFrom);
   
$zip->addEmptyDir($localDir);
   
    foreach (
$filesToAdd as $file) {
       
$zip->addFile($currentDir . $file, $localDir . $file);
    }
}

$zip->close();
?>
D.Jann
7.10.2008 14:26
I've brought a little modification to dayjo's code, so it wouldn't re-create the whole structure of your working drive in the zip file:

<?php
// Function to recursively add a directory,
// sub-directories and files to a zip archive
function addFolderToZip($dir, $zipArchive, $zipdir = ''){
    if (
is_dir($dir)) {
        if (
$dh = opendir($dir)) {

           
//Add the directory
           
if(!empty($zipdir)) $zipArchive->addEmptyDir($zipdir);
          
           
// Loop through all the files
           
while (($file = readdir($dh)) !== false) {
          
               
//If it's a folder, run the function again!
               
if(!is_file($dir . $file)){
                   
// Skip parent and root directories
                   
if( ($file !== ".") && ($file !== "..")){
                       
addFolderToZip($dir . $file . "/", $zipArchive, $zipdir . $file . "/");
                    }
                  
                }else{
                   
// Add the files
                   
$zipArchive->addFile($dir . $file, $zipdir . $file);
                  
                }
            }
        }
    }
}
?>

If you don't specify the third parameter (zipdir), the directory you're adding will be added at the root of the zip file.

D.Jann
pagetronic
12.09.2008 12:53
addEmptyDir doesn't exist now,
use $zip->addFile($file, $dir.$fichier);

nothing on the net about this,

addEmptyDir work on Ubuntu but not on Debian Etch
Anonymous
25.08.2008 0:28
Here's a simple recurring function to add a directory, all sub-directories and all files to an already created zip file;

<?php
// Function to recursively add a directory,
// sub-directories and files to a zip archive
function addFolderToZip($dir, $zipArchive){
    if (
is_dir($dir)) {
        if (
$dh = opendir($dir)) {

           
//Add the directory
           
$zipArchive->addEmptyDir($dir);
           
           
// Loop through all the files
           
while (($file = readdir($dh)) !== false) {
           
               
//If it's a folder, run the function again!
               
if(!is_file($dir . $file)){
                   
// Skip parent and root directories
                   
if( ($file !== ".") && ($file !== "..")){
                       
addFolderToZip($dir . $file . "/", $zipArchive);
                    }
                   
                }else{
                   
// Add the files
                   
$zipArchive->addFile($dir . $file);
                   
                }
            }
        }
    }
}
?>

Would be nice to see more input on these functions :)

Dayjo
benjamin dot seiller at antwerpes dot de
21.07.2008 13:37
There is kind of a bug in the method
ZipArchive::addFile
which affects the class ZipFolder below.
It is related to the numer of max filehandles of the OS.

As workaround add a file-counter to the class and close + reopen the archive if a certain number of files (directories count as files!) is reached.

For more details see here:
http://de.php.net/manual/en/function.ziparchive-addfile.php
or go directly here
http://bugs.php.net/bug.php?id=40494
or here
http://pecl.php.net/bugs/bug.php?id=9443
jerome at buttered-cat dot com
15.10.2007 22:20
Here's some code I wrote to add a NON-empty directory to ZipArchive, it's done pretty quickly but so far works great.

<?php
class ZipFolder {
    protected
$zip;
    protected
$root;
    protected
$ignored_names;
   
    function
__construct($file, $folder, $ignored=null) {
       
$this->zip = new ZipArchive();
       
$this->ignored_names = is_array($ignored) ? $ignored : $ignored ? array($ignored) : array();
        if (
$this->zip->open($file, ZIPARCHIVE::CREATE)!==TRUE) {
            throw new
Exception("cannot open <$file>\n");
        }
       
$folder = substr($folder, -1) == '/' ? substr($folder, 0, strlen($folder)-1) : $folder;
        if(
strstr($folder, '/')) {
           
$this->root = substr($folder, 0, strrpos($folder, '/')+1);
           
$folder = substr($folder, strrpos($folder, '/')+1);
        }
       
$this->zip($folder);
       
$this->zip->close();
    }
   
    function
zip($folder, $parent=null) {
       
$full_path = $this->root.$parent.$folder;
       
$zip_path = $parent.$folder;
       
$this->zip->addEmptyDir($zip_path);
       
$dir = new DirectoryIterator($full_path);
        foreach(
$dir as $file) {
            if(!
$file->isDot()) {
               
$filename = $file->getFilename();
                if(!
in_array($filename, $this->ignored_names)) {
                    if(
$file->isDir()) {
                       
$this->zip($filename, $zip_path.'/');
                    }
                    else {
                       
$this->zip->addFile($full_path.'/'.$filename, $zip_path.'/'.$filename);
                    }
                }
            }
        }
    }
}
// full path used to demonstrate it's root-path stripping ability
$zip = new ZipFolder('/tmp/test.zip', dirname(__FILE__).'/templates/', '.svn');
?>



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)