Oihana PHP

tarDirectory.php

Table of Contents

Functions

tarDirectory()  : string
Creates a tar archive from a directory with specified compression.

Functions

tarDirectory()

Creates a tar archive from a directory with specified compression.

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

This function creates a compressed (or uncompressed) tar 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. Otherwise, it copies filtered files to a temporary directory and archives from there.

Parameters
$directory : string

The source directory to archive.

$compression : string|null = CompressionType::GZIP

Compression type (e.g. gzip, bzip2, none). Default is gzip compression.

$outputPath : string|null = null

Optional output archive path. If null, defaults to directory name plus extension based on compression.

$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.

throws
FileException

If there are issues writing files or archives.

throws
UnsupportedCompressionException

If an unsupported compression type is specified.

throws
RuntimeException

If no files match filtering criteria.

example
// Create a gzip compressed tar archive from directory /var/www/html
$archive = tarDirectory('/var/www/html');
echo $archive; // /var/www/html.tar.gz

// Create a bz2 compressed archive, excluding .git and node_modules folders
$archive = tarDirectory(
    '/var/www/html',
    CompressionType::BZIP2,
    null,
    [
        TarOption::EXCLUDE => ['.git', 'node_modules'],
    ]
);

// Create an archive with a custom filter callback and add metadata
$archive = tarDirectory(
    '/var/www/html',
    CompressionType::NONE,
    '/backups/html_backup.tar',
    [
        TarOption::FILTER => function(string $filePath): bool {
            // Only include PHP files
            return str_ends_with($filePath, '.php');
        },
        TarOption::METADATA => [
            'createdBy' => 'admin',
            'description' => 'Backup of PHP source files',
        ],
    ]
);
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
string

Returns the full path to the created archive file.


        
On this page

Search results