Content · Programming · PHP

PHP gzwrite() Function: Usage and Examples

Understand PHP gzwrite() with three examples, return behavior, important pitfalls, and related operations.

1 views Published Oct 16, 2026 Updated Oct 16, 2026

Use gzwrite() when you need to writes uncompressed bytes to a gzip stream in a PHP application. The examples below show the actual operation and its limitations.

What Is gzwrite() in PHP?

Writes uncompressed bytes to a gzip stream. The exact signature supported by your installation depends on its PHP version and enabled extensions.

Its syntax is:

gzwrite($stream, string $data, ?int $length = ...): int|false

Parameters and return value: The parameter types, optional arguments, references, and return type are shown in the signature above. Optional parameters are marked with an ellipsis in this reference signature.

Example 1: Basic Usage

<?php

$path = tempnam(sys_get_temp_dir(),"gzip_"); $file = gzopen($path,"wb"); echo gzwrite($file,"Hello"); gzclose($file); unlink($path);

Output:

5

Example 2: Different Input or Behavior

<?php

$path = tempnam(sys_get_temp_dir(),"gzip_"); $file = gzopen($path,"wb"); gzwrite($file,"ABCD"); gzclose($file); $file = gzopen($path,"rb"); echo gzread($file,20); gzclose($file); unlink($path);

Output:

ABCD

Practical Example: Applying the Function

<?php

$path = tempnam(sys_get_temp_dir(),"gzip_"); $file = gzopen($path,"wb"); foreach (["alpha","beta"] as $row) gzwrite($file,$row."
"); gzclose($file); echo "Archive written"; unlink($path);

Output:

Archive written

Important Behavior and Edge Cases

The return value is the number of uncompressed input bytes written, not the gzip file size.

Comparison With Related Functions

ApproachDifference
gzwrite()Writes uncompressed bytes to a gzip stream.
Related operationgzputs() is an alias of gzwrite().

Common Beginner Mistakes

MistakeCorrect Approach
Ignoring the function-specific limitationThe return value is the number of uncompressed input bytes written, not the gzip file size.
Confusing this function with a related operationgzputs() is an alias of gzwrite().

Key Takeaways

  • Writes uncompressed bytes to a gzip stream.
  • The return value is the number of uncompressed input bytes written, not the gzip file size.
  • gzputs() is an alias of gzwrite().

Use gzwrite() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.

Share this resourceSend this page to someone who may find it useful.