scytale
scytale

Reputation: 1399

PHP to extract "some-dir/file.ext" from TAR to "another-dir/file.ext"

I use a .tar.gz created monthly by a 3rd party. I can unzip to a .tar; but I am unable to override the tar directory name when I extract files from the tar.

The tar has a single folder "dirname_latestDate" containing a number of files. I was hoping that by specifying individual files for extraction then the tar's "folder" would be ignored (test script cobbled from code on stackoverflow and elsewhere).

$archive = new PharData($theTar);
// error cheecking excluded    
foreach($archive as $entry) {
  $extractDir = basename($file) . '/';
  if($file->isDir()) {
    $dir = new PharData($file->getPathname());          
    foreach($dir as $child) {
      $extract_file = $extractDir . basename($child);
      $archive->extractTo('/mypath/my-dir', $extract_file, true);
    }
  }
}

But this still results in the files being placed in a sub-directory named as per tar folder e.g. /mypath/my-dir/unwanted-tar-dirname/file.ext.

I can copy the file from the sub-dir and then delete but this seems ineffficient and unnecessary. Is there any way to override the Tar folder name on un-tar? The tar contains one file of about 4MB (uncompressed) and a few other miniscule files.

Upvotes: 0

Views: 423

Answers (1)

cweiske
cweiske

Reputation: 31078

No, you can't change the output file name directly with extractTo.

You could however use file_put_contents in combination with $phar['filepath]->getContent() to extract the file manually.

Upvotes: 3

Related Questions