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
| Approach | Difference |
|---|---|
gzwrite() | Writes uncompressed bytes to a gzip stream. |
| Related operation | gzputs() is an alias of gzwrite(). |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring the function-specific limitation | The return value is the number of uncompressed input bytes written, not the gzip file size. |
| Confusing this function with a related operation | gzputs() 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.