katzlbtjunk's method is certainly shorter, but it is unusable for anything except small files. It would try to load the whole file into memory, then create an entire compressed copy, and only then write it to disk. The other method given below will not exhaust memory like that.

Read the description of gzwrite() very carefully. If the 'length' option is not specified, then the input data will have slashes stripped on systems where magic quotes are enabled. This is important information to know when compressing files.