Oihana PHP

tar.php

Table of Contents

Functions

tar()  : string
Creates a tar archive from one or more files and/or directories.

Functions

tar()

Creates a tar archive from one or more files and/or directories.

tar(string|array<string|int, string> $paths[, string|null $outputPath = null ][, string|null $compression = CompressionType::GZIP ][, string|null $preserveRoot = null ]) : string

This function supports adding multiple paths (files or directories) to a tar archive, with optional compression (gzip, bzip2, or none). It can preserve the root directory structure inside the archive, and generates a unique temporary archive if no output path is specified.

Empty directories are preserved in the archive.

Parameters
$paths : string|array<string|int, string>

Absolute path(s) to file(s) or directory(ies) to include in the archive.

$outputPath : string|null = null

Optional full path to the final archive file to create. If null, an automatic unique filename with timestamp is generated in the system temp directory.

$compression : string|null = CompressionType::GZIP

Compression type to use on the tar archive. Supported values are defined in CompressionType, defaults to CompressionType::GZIP.

$preserveRoot : string|null = null

If set, paths inside the archive will be stored relative to this directory, allowing to preserve directory structure when extracting. Must be an absolute path.

Tags
throws
FileException

If any of the provided paths does not exist or is invalid.

throws
UnsupportedCompressionException

If the requested compression type is not supported by the system.

throws
DirectoryException

If the temporary directory cannot be created or accessed.

throws
RuntimeException

If no files are added to the archive or if an error occurs during creation, including inability to rename temporary files.

see
CompressionType
example

Archive a single file, auto-named, gzip compressed (default):

$tarPath = tar('/var/www/html/index.php');

Archive a directory with bzip2 compression:

$tarPath = tar('/var/www/html', '/tmp/site.tar.bz2', CompressionType::BZIP2);

Archive multiple files with no compression:

$tarPath = tar
(
   ['/etc/hosts', '/etc/hostname'],
   '/tmp/config.tar',
   CompressionType::NONE
);

Archive directory with root preserved (relative paths):

$tarPath = tar
(
    '/var/www/html/project',
    '/tmp/project.tar.gz',
    CompressionType::GZIP,
    '/var/www/html'
);
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
string

Returns the full path to the created tar archive file.


        
On this page

Search results