zip

Compress files and folders in tar (Linux)

GZIP and TAR are two different utilities bound by the same cause. Compressing files and making file catalogs.

To compress a file, simply gzip it:

$> gzip database_dump.sql

That will compress the database_dump.sql file, and rename it to database_dump.sql.gz. Easy, and to uncompress it:

$> gunzip database_dump.sql.gz

That will restore the uncompressed version and rename to file back to .sql

But, what if you want to do more than one, or a folder. GZIP is not the tool, however it is used.

You need to TAR the files (which creates one file with the specified files in) and then gzip it:

$> tar -cvzpf compressed_file.tgz foldername

That will compress all files in the foldername folder into a file specified, and it will GZIP it for you.

If you want to just compress a few files, then instead of using the foldername have a list of the files separated by space

$> tar -cvzpf compressed_files.tgz file1 file2 file3

Easy, so to unTar them:

$> tar -zxvf compressed_file.tgz

The above will extract the files to the current folder, if you want them somewhere else:

$> tar -C /foldername -zxvf compressed_file.tgz

The above will extract the files to the /foldername folder.

Hope that helps a little.

 

PHP Create a ZIP file

I was just playing around with PHP’s ability to create compressed files, and I had a problem. My ZIP file was not getting created but I wasn’t getting any errors.

$zip = new ZipArchive();
$zipFile = '/tmp/' . uniqid() . '.zip';

if (file_exists($zipFile)) {
    unlink($zipFile);
}

$zip->open($zipFile, ZIPARCHIVE::CREATE);

foreach ($files as $type => $file) {
    $zip->addFile($file);
}

$zip->close();

Now, pay particular attention to the files you are adding using addFile() as if you have entered them wrong, you won’t get an error message, and infact, if you use $zip->getStatusString() you will receieve a “No error” message – completely throwing you off the scent.

More information about ZipArchive can be found at http://www.php.net/manual/en/class.ziparchive.php