How7o
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Extract a .tar.gz Archive in PHP
Share
How7oHow7o
Font ResizerAa
  • OS
Search
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Follow US
© 2024–2026 How7o. All rights reserved.
How7o > Free Laravel, PHP, WordPress & Server Tutorials > Web Development > How to Extract a .tar.gz Archive in PHP
Web Development

How to Extract a .tar.gz Archive in PHP

how7o
By how7o
Last updated: May 22, 2026
5 Min Read
Extract a .tar.gz archive in PHP with PharData
SHARE

To extract a .tar.gz file with PHP on shared hosting that blocks exec(), use the built-in PharData class. The pattern is two steps: decompress() removes the gzip layer, then extractTo() unpacks the resulting .tar into a destination directory.

Contents
  • The two-step recipe
  • Cleaning up the intermediate .tar
  • One-call variant (newer PHP)
  • When extraction silently does nothing
  • Frequently asked questions
  • Related guides
  • References

Last verified: 2026-05-17 on PHP 8.1 and 8.3. Originally published 2022-07-19, rewritten and updated 2026-05-17.

The two-step recipe

<?php
try {
    $file_path = "/path/to/myfile";

    // 1. Decompress the gzip layer -> /path/to/myfile.tar
    $p = new PharData("{$file_path}.tar.gz");
    $p->decompress();

    // 2. Extract the tar archive
    $phar = new PharData("{$file_path}.tar");
    $phar->extractTo("/destination/path");

} catch (Exception $e) {
    error_log("tar.gz extract failed: " . $e->getMessage());
}

After decompress(), there’s an uncompressed myfile.tar sitting next to your .tar.gz. The second step opens that tar and writes every entry into /destination/path. extractTo() creates the destination directory if it doesn’t exist.

PHP extract .tar.gz with PharData — decompress gzip, extractTo destination, cleanup intermediate

Cleaning up the intermediate .tar

$archive = "{$file_path}.tar.gz";
$tar     = "{$file_path}.tar";

try {
    (new PharData($archive))->decompress();
    (new PharData($tar))->extractTo("/destination/path", null, true);
} finally {
    if (file_exists($tar)) {
        unlink($tar);
    }
}

The third argument true to extractTo() overwrites existing files in the destination. The finally block ensures the intermediate .tar is removed even if extraction throws — important for shared hosts with disk quotas.

One-call variant (newer PHP)

(new PharData('/path/to/myfile.tar.gz'))->extractTo('/destination/path', null, true);

On PHP 8+, PharData handles the gzip layer transparently in many cases — no separate decompress() step needed. If it errors out (which still happens on certain archives), fall back to the explicit two-step recipe above.

When extraction silently does nothing

  • Wrong file extension on disk. PharData infers format from the file name, not the bytes. A .tar.gz renamed to .tgz won’t be read as gzip. Rename or pass Phar::TAR/Phar::GZ flags.
  • Phar read-only mode. If phar.readonly = 1 in php.ini, decompress() on a non-Phar archive still works, but write-style operations on .phar archives don’t. Reading and extracting .tar.gz is unaffected.
  • Destination permissions. If your script user can’t write to /destination/path, extractTo() throws a PharException. Catch it and report.

Frequently asked questions

Why does PharData create a .tar file when I decompress?

.tar.gz is two layers — tar bundles many files into one, gzip compresses the bundle. PharData::decompress() only handles the gzip layer, leaving the uncompressed .tar behind. You then call extractTo() on that .tar to write out the individual files. It’s the same two-step model as gunzip foo.tar.gz followed by tar -xf foo.tar.

Do I need any PHP extensions for this to work?

The phar extension must be enabled — it’s bundled in core and on by default on every modern PHP build. You also need zlib compiled in for gzip support, which is also default. On shared hosting where you can’t change PHP config, both are almost always present. Check with php -m | grep -iE 'phar|zlib'.

How do I delete the intermediate .tar after extraction?

Just unlink() it after extractTo() succeeds. For tidiness, wrap the whole thing so the intermediate file is cleaned up even on error: extract inside a try, then unlink in a finally. Otherwise a failed extraction leaves the .tar sitting on disk.

Is there a one-liner that handles gzip + tar together?

Yes — (new PharData('file.tar.gz'))->extractTo('/dest') works in one call on newer PHP, because PharData can read the gzip layer transparently. The two-step approach in the source is the historically-safe pattern that always worked, including on older PHP where transparent gzip wasn’t reliable.

Related guides

  • How to Create a Folder If It Does Not Exist in PHP
  • How to Zip Multiple Files and Directories in Linux
  • How to Enable the PHP DOM Extension

References

PharData manual: php.net/manual/en/class.phardata.php. PharData::decompress(): php.net/manual/en/phardata.decompress.php. PharData::extractTo(): php.net/manual/en/phardata.extractto.php.

TAGGED:configurationfilesystemphp

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
[mc4wp_form]
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article Enable the PHP DOM extension on a Linux server How to Enable the PHP DOM Extension
Next Article Fix missing PHP Authorization header on Apache and cPanel How to Fix Missing Authorization Header in PHP Requests
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

FacebookLike
XFollow
PinterestPin
InstagramFollow
Most Popular
Set vi as the default editor in Ubuntu — a terminal opening the vim editor
How to Set vi (Vim) as the Default Editor in Ubuntu
June 8, 2026
rsync says ALL DONE but files are missing — a terminal showing ALL DONE next to an empty folder
rsync Says “ALL DONE” but Files Are Missing: How to Verify
June 8, 2026
Migrate a website to a new server with rsync — files copying from an old server to a new one over SSH
How to Migrate a Website to a New Server With rsync
June 8, 2026
Bun runtime — faster JS toolkit replacing npm in Laravel projects
How to Install Bun Runtime on Ubuntu (And Use It in a Laravel Project)
May 24, 2026
Tailscale mesh — peer-to-peer connections between devices, coordination server
How to Install Tailscale on Ubuntu (Zero-Config Mesh VPN for Self-Hosters)
May 24, 2026

You Might Also Like

Fix DKIM not signing emails in aaPanel
Server Management

How to Fix DKIM Not Signing Emails in aaPanel

5 Min Read
Securely hash passwords in PHP with password_hash
Web Development

Securely Hash Passwords in PHP (password_hash, Argon2id)

6 Min Read
DataTables server-side Ajax pagination with Laravel
Web Development

How to Create Ajax-Based Pagination in DataTables

6 Min Read
Use a JavaScript variable as an object key
Web Development

How to Use a Variable as an Object Key in JavaScript

5 Min Read
How7o

We provide tips, tricks, and advice for improving websites and doing better search.

Tools

  • Age Calculator
  • Word Counter
  • Image Upscaler
  • Password Generator
  • QR Code Generator
  • See all tools→

Pranks

  • Fake Blue Screen Prank
  • Hacker Typer
  • Fake iMessage Generator
  • Windows XP Crash Prank
  • Windows 11 Update Prank
  • See all prank screens →

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service
  • Sitemap
© 2024–2026 How7o. All rights reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?