Content · Programming · PHP

PHP gzread() Function: Usage and Examples

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

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

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

ApproachDifference
gzread()Reads uncompressed bytes from an open gzip stream.
Related operationgzgets() reads a whole line; gzread() reads a requested number of bytes.

Common Beginner Mistakes

MistakeCorrect Approach
Ignoring the function-specific limitationThe length is a byte count and reads may return less data than requested.
Confusing this function with a related operationgzgets() 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.

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