Use gzcompress() when you need to compresses a string using the zlib data format in a PHP application. The examples below show the actual operation and its limitations.
What Is gzcompress() in PHP?
Compresses a string using the zlib data format. The exact signature supported by your installation depends on its PHP version and enabled extensions.
Its syntax is:
gzcompress(string $data, int $level = ..., int $encoding = ...): 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
$compressed = gzcompress("Hello Hello"); echo gzuncompress($compressed);
Output:
Hello Hello
Example 2: Different Input or Behavior
<?php
$compressed = gzcompress(str_repeat("A",100)); echo strlen($compressed) < 100 ? "Smaller" : "Not smaller";
Output:
Smaller
Practical Example: Applying the Function
<?php
$message = "Saved configuration"; $packed = gzcompress($message, 6); echo gzuncompress($packed);
Output:
Saved configuration
Important Behavior and Edge Cases
A compressed value is binary data, not encrypted and not necessarily smaller than the original.
Comparison With Related Functions
| Approach | Difference |
|---|---|
gzcompress() | Compresses a string using the zlib data format. |
| Related operation | gzdeflate() creates raw DEFLATE data instead of zlib-wrapped data. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring the function-specific limitation | A compressed value is binary data, not encrypted and not necessarily smaller than the original. |
| Confusing this function with a related operation | gzdeflate() creates raw DEFLATE data instead of zlib-wrapped data. |
Key Takeaways
- Compresses a string using the zlib data format.
- A compressed value is binary data, not encrypted and not necessarily smaller than the original.
- gzdeflate() creates raw DEFLATE data instead of zlib-wrapped data.
Use gzcompress() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.