How to compress and decompress text an encode/decode using base64 functions:
1. Compress and Encode to Base64
function Compress2Base64($str, $gztype='deflate') { switch($gztype) { case 'deflate' : return base64_encode( gzdeflate($str, 9) ); case 'compress' : return base64_encode( gzcompress($str, 9) ); case 'encode' : return base64_encode( gzencode($str, 9) ); default: return base64_encode( gzdeflate($str, 9) ); } }
2. Decode from Base64 and decompress string/text
function deCompressBase64($str, $gztype='deflate') { switch($gztype) { case 'deflate' : return @gzinflate(base64_decode($str)); case 'compress' : return @gzuncompress(base64_decode($str)); case 'encode' : return @gzdecode(base64_decode($str)); default: return @gzinflate(base64_decode($str)); } }
where $gztype
can take this values:
- deflate,
- compress
- encode
but as an idea, deflate is best for size;
Note: To decode you must use the same value for
$gztype
.
More compact variants for the above functions:
1. Compress and Encode to Base64
function Compress2Base64($str, $gztype=ZLIB_ENCODING_RAW ) { return base64_encode( zlib_encode($str, $gztype, 9) ); }
2. Decode from Base64 and decompress string/text
function deCompressBase64($str, $gztype='deflate') { return @zlib_decode(base64_decode($str)); }
where $gztype
can take this values:
- ZLIB_ENCODING_RAW
- ZLIB_ENCODING_DEFLATE
- ZLIB_ENCODING_GZIP
ZLIB_ENCODING_RAW is better (shorter result)
Be First to Comment