Reza
Reza

Reputation: 523

Adding files to a specific subdirectory of a zip archive

This function will add a directory (including files and subdirectories) to a zip archive.

private function zip($source, $destination) {
    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }

    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        return false;
    }

    $source = str_replace('\\', '/', realpath($source));

    if (is_dir($source) === true) {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

        foreach ($files as $file) {
            $file = str_replace('\\', '/', $file);

            // Ignore "." and ".." folders
            if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
                continue;

            $file = realpath($file);

            if (is_dir($file) === true) {
                $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
            }
            else if (is_file($file) === true) {
                $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
        }
    }
  }

My problem is that the directory gets added to the root of the zip archive. But I want it to be added to a specific subdirectory. How can I do this?

Upvotes: 0

Views: 168

Answers (1)

Timur
Timur

Reputation: 51

You can prepend subdirectory name to the file (or directory) name before adding it to an archive:

$file = realpath($file);
$subdir = "sub/dir/";

if (is_dir($file) === true) {
    $zip->addEmptyDir($subdir . str_replace($source . '/', '', $file . '/'));
} else if (is_file($file) === true) {
    $zip->addFromString($subdir . str_replace($source . '/', '', $file), file_get_contents($file));
}

In the ZipArchive::addFile method you can use $localname parameter:

$zip->addFile($file, $subdir . str_replace($source . '/', '', $file));

Upvotes: 1

Related Questions