3

I want to compress a .txt file in PHP while maintaining the file extension. When I decompress the .gz file the extension (.txt) in the .gz file is removed. (test.txt becomes -> test)

Here's a example of my PHP code to compress test.txt into a .gz file:

<?php

// Name of the file we are compressing
$file = "test.txt";

// Name of the gz file we are creating
$gzfile = "test.gz";

// Open the gz file (w9 is the highest compression)
$fp = gzopen ($gzfile, 'w9');

// Compress the file
gzwrite ($fp, file_get_contents($file));

// Close the gz file and we are done
gzclose($fp);

?>

Does someone knows what I'm doing wrong? Or is this because gzip limations?

  • gz doesn't save anywhere the extension. gzip simply removes the .gz when deflating. (It's not an archive, it's only a compression of a file) – bwoebi May 20 '13 at 12:56
  • If I'm looking at this correctly, I don't think you're loading the file into the .gz file... you're loading the file contents into the gz file. There is no 'file name' being preserved here, with or without the file extension. Are you trying to build a tar archive? At a guess... what is the contents of test.txt? Is it possibly 'test'? – Wolfman Joe May 20 '13 at 13:00
  • @bwoebi I didn't know that, is `.tar.gz` a good choice? @WolfmanJoe The contents of `test.txt` is indeed `test`. I use now a `.tar.gz` PHP compressor but that didn't work on some servers, so I thought `.gz` is a better choice. –  May 20 '13 at 13:26
  • You don't need a tar for a single file. Use file.txt.gz. – bwoebi May 20 '13 at 14:02
  • 1
    @bwoebi - the follow-up question of 'does directories also not work when compressed in `.gz` format' explains why I was asking after tar. Gerrit, to compress a directory of files, you'll need to use something other then just simple gz compression. – Wolfman Joe May 20 '13 at 18:03

1 Answers1

3

Normally gzip does not use the name in the gzip header when decompressing, and you didn't store a name in the header anyway. It simply removes the .gz from the file name. You would need to name the file test.txt.gz to get it to decompress to test.txt.

Mark Adler
  • 101,978
  • 13
  • 118
  • 158
  • Thanks for the answer! Does directories also not work when compressed in `.gz` format? –  May 20 '13 at 17:09
  • Certainly not. gzip is intended to compress a single file or stream of data. You need to use formats like `.tar.gz` or `.zip` to store multiple files and directory structures. – Mark Adler May 20 '13 at 20:45