Oihana PHP

zipDirectory.php

Table of Contents

Functions

zipDirectory()  : string
Creates a zip archive from a directory.

Functions

zipDirectory()

Creates a zip archive from a directory.

zipDirectory(string $directory[, string|null $compression = CompressionType::ZIP ][, string|null $outputPath = null ][, array<string|int, mixed> $options = [] ]) : string

This function creates a zip archive from the given directory. It supports filtering files by exclude patterns, by a callback filter function, and adding optional metadata saved as .metadata.json inside the archive.

If no filters or metadata are provided, it simply creates the archive directly from the directory (preserving its root). Otherwise, it copies the filtered files to a temporary directory and archives from there.

Parameters
$directory : string

The source directory to archive.

$compression : string|null = CompressionType::ZIP

Per-entry compression method (CompressionType::ZIP — DEFLATE, default — or CompressionType::NONE — stored).

$outputPath : string|null = null

Optional output archive path. If null, defaults to the directory name plus the .zip extension.

$options : array<string|int, mixed> = []

Additional options:

  • exclude => string[] list of glob patterns or file names to exclude
  • filter => callable|null a function (string $filepath): bool
  • metadata => array<string, string> extra metadata to embed in .metadata.json
Tags
throws
DirectoryException

If the source directory does not exist or is inaccessible.

FileException

If there are issues writing files or archives.

UnsupportedCompressionException

If an unsupported compression method is specified.

RuntimeException

If no files match the filtering criteria.

example
// Create a zip archive from directory /var/www/html
$archive = zipDirectory('/var/www/html');
echo $archive; // /var/www/html.zip

// Create a stored (uncompressed) archive, excluding .git and node_modules
$archive = zipDirectory(
    '/var/www/html',
    CompressionType::NONE,
    null,
    [ ZipOption::EXCLUDE => ['.git', 'node_modules'] ]
);

// Create an archive with a custom filter callback and embedded metadata
$archive = zipDirectory(
    '/var/www/html',
    CompressionType::ZIP,
    '/backups/html_backup.zip',
    [
        ZipOption::FILTER   => fn( string $filePath ): bool => str_ends_with( $filePath , '.php' ),
        ZipOption::METADATA => [ 'createdBy' => 'admin' , 'description' => 'PHP source backup' ],
    ]
);
author

Marc Alcaraz (ekameleon)

since
1.2.0
Return values
string

Returns the full path to the created archive file.

On this page

Search results