Create .tar.gz file with PHP
The project I'm working on requires creating .tar.gz archives and submitting it to an external service. This external service only works with .tar.gz, so another type of archive is out of the question. The server my code is running on does not allow system call access. Thus, system
, exec
, backticks etc. Are not bueno. This means that I have to rely on a pure PHP implementation to generate .tar.gz files.
With a bit of research, it seems like it PharData
will be helpful to get things done . However, I hit the wall with it and need guidance.
Consider the following folder layout:
parent folder
- child folder 1
- child folder 2
- file1
- file2
I am using the below code snippet to create a .tar.gz archive, which does the trick, but there is a minor issue with the end result, it does not contain the parent folder, but everything inside it.
$pd = new PharData('archive.tar');
$dir = realpath("parent-folder");
$pd->buildFromDirectory($dir);
$pd->compress(Phar::GZ);
unset( $pd );
unlink('archive.tar');
When the archive is created, it should contain the exact directory mentioned above. Using the above code snippet, the archive contains everything except the parent folder, which is the offending external service:
- child folder 1
- child folder 2
- file1
- file2
The description buildFromDirectory
mentions the following, so it doesn't contain the parent folder in the archive, it's clear:
Create tar / zip archive from files in directory.
I also tried using buildFromIterator
, but the end result is the same with it too, i.e. the parent folder is not included in the archive. I managed to get the desired result with help addFile
, but it's painfully slow .
After doing a little more research, I found the following library: https://github.com/alchemy-fr/Zippy . But this requires support composer
that is not available on the server. I would appreciate it if someone could guide me towards the end result. I am also open to using some other methods or libraries as long as they are pure PHP implementation and do not require any external dependencies. Not sure if it helps, but the server that the code will run on has PHP 5.6
source to share
Use the parent "parent-folder" as the base for Phar::buildFromDirectory()
and use your second parameter to limit the results to only "parent folder", for example:
$parent = dirname("parent-folder");
$pd->buildFromDirectory($parent, '#^'.preg_quote("$parent/parent-folder/", "#").'#');
$pd->compress(Phar::GZ);
source to share