Handle PHP zlib Warnings and Exceptions Consistently

PHP zlib functions do not use one universal failure mechanism. Invalid argument types can throw TypeError, invalid values can throw ValueError, and corrupt compressed data may still raise a warning and return false. Handle the operation at a narrow boundary.

Last updated: November 12, 2026.

<?php

function inflatePayload(string $compressed, int $maxBytes): string
{
    if ($maxBytes < 1 || $maxBytes > 10_000_000) {
        throw new InvalidArgumentException('Invalid decompression limit');
    }

    set_error_handler(static function (
        int $severity,
        string $message,
        string $file,
        int $line
    ): never {
        throw new ErrorException($message, 0, $severity, $file, $line);
    });

    try {
        $result = gzinflate($compressed, $maxBytes);
    } finally {
        restore_error_handler();
    }

    if ($result === false) {
        throw new RuntimeException('Compressed payload could not be decoded');
    }

    return $result;
}

The custom error handler exists only around gzinflate() and is always restored. The output limit prevents an untrusted compressed payload from expanding without an application-defined bound.

Separate configuration errors from data errors

The deflate_init manual defines accepted encoding constants and option ranges. Validate configuration before creating a context. The PHP 8.6 migration guide documents additional TypeError behavior for non-integer zlib options, so do not depend on an older warning-only path.

Catch TypeError or ValueError where invalid program configuration can be reported meaningfully. Do not convert every throwable into “bad compressed data,” because that hides a deployment or coding mistake.

Bound and verify decompression

The gzinflate documentation accepts a maximum output length and returns a string or false. Set a limit based on the business payload, not on available memory. Also limit the compressed input size before calling the decoder.

Avoid the @ operator, which discards diagnostic context. If the application converts warnings to exceptions, scope that handler to the single library call and restore it in finally. Log the operation and safe size metadata, but not sensitive decompressed content. Test valid data, truncated data, random bytes, and a payload that exceeds the configured output limit.

Related Web Cheat Sheet guides

Sergey Kornilov

Sergey Kornilov