Use gzread() when you need to reads uncompressed bytes from an open gzip stream in a PHP application. The examples below show the actual operation and its limitations.
What Is gzread() in PHP?
Reads uncompressed bytes from an open gzip stream. The exact signature supported by your installation depends on its PHP version and enabled extensions.
Its syntax is:
gzread($stream, int $length): string|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"); gzwrite($file,"ABCDE"); gzclose($file); $file = gzopen($path,"rb"); echo gzread($file,3); gzclose($file); unlink($path);
Output:
ABC
Example 2: Different Input or Behavior
<?php
$path = tempnam(sys_get_temp_dir(),"gzip_"); $file = gzopen($path,"wb"); gzwrite($file,"Hello"); gzclose($file); $file = gzopen($path,"rb"); echo gzread($file,10); gzclose($file); unlink($path);
Output:
Hello
Practical Example: Applying the Function
<?php
$path = tempnam(sys_get_temp_dir(),"gzip_"); $file = gzopen($path,"wb"); gzwrite($file,"data record"); gzclose($file); $file = gzopen($path,"rb"); $text = ""; while (!gzeof($file)) { $part = gzread($file,4); if ($part === false || $part === "") break; $text .= $part; } echo $text; gzclose($file); unlink($path);
Output:
data record
Important Behavior and Edge Cases
The length is a byte count and reads may return less data than requested.
Comparison With Related Functions
| Approach | Difference |
|---|---|
gzread() | Reads uncompressed bytes from an open gzip stream. |
| Related operation | gzgets() reads a whole line; gzread() reads a requested number of bytes. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring the function-specific limitation | The length is a byte count and reads may return less data than requested. |
| Confusing this function with a related operation | gzgets() reads a whole line; gzread() reads a requested number of bytes. |
Key Takeaways
- Reads uncompressed bytes from an open gzip stream.
- The length is a byte count and reads may return less data than requested.
- gzgets() reads a whole line; gzread() reads a requested number of bytes.
Use gzread() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.