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
Run Laravel queue workers with Supervisor
How to Run Laravel Queue Workers in Production with Supervisor
May 23, 2026
Nginx as a reverse proxy for a Node.js app on Ubuntu
How to Set Up Nginx as a Reverse Proxy for Node.js on Ubuntu
May 23, 2026
Install and configure Redis on Ubuntu for Laravel and WordPress
How to Install and Configure Redis on Ubuntu (for Laravel & WordPress)
May 23, 2026
Harden a fresh Ubuntu VPS with UFW, Fail2Ban, and SSH key auth
How to Harden a Fresh Ubuntu VPS: UFW + Fail2Ban + SSH Key Auth
May 23, 2026
Set up Let's Encrypt SSL with Certbot on Ubuntu
How to Set Up Let’s Encrypt SSL with Certbot on Ubuntu (Apache & Nginx)
May 23, 2026

You Might Also Like

Laravel get config variable — config() helper and Config facade resolving dotted keys
Web Development

How to Get Config Variables in Laravel

7 Min Read
Zip multiple files and directories on Linux — zip -r command
Server Management

How to Zip Multiple Files and Directories on Linux

5 Min Read
Remove the Other Favorites button on the Microsoft Edge favorites bar
OS

How to Remove the “Other Favorites” Button in Microsoft Edge

4 Min Read
Replace Broken Images Automatically with JavaScript
Web Development

Replace Broken Images Automatically with JavaScript (and jQuery)

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?