4

I have a php file that do:

echo(gzcompress("TEST COMPRESS"));

and on javascript i do a request on php and i want a function that do the same of gzuncompress(data) for take the result = "TEST COMPRESS" again on client side.

EDIT: Thank you @aaronk6, zlib worked!

If someone ready this question, the zlib will works if the php is with gzencode(), gzcompress will not work.

2 Answers2

2

As @SLaks pointed out, this is might be pointless, however here’s an answer to your question.

Browsers do not have a uncompress method that is accessible from JavaScript, so there’s no equivalent. When you want to decompress gzipped data in JavaScript, you will need to use a JavaScript implementation of the gzip algorithm.

There’s zlib.js which seems to be capable of doing this.

aaronk6
  • 2,701
  • 1
  • 19
  • 28
  • 1
    Heyyy Thank you! Worked Perfect!! I just had tochange in php the gzcompress() to gzencode() and works the Zlib.Gunzip(data).decompress() – Matheus Benedet Feb 27 '15 at 22:10
0

If you have PHP running on your server, and you want to decompress a zlib-compressed string in Javascript, an alternative to using the zlib.js library would be to use the Fetch API to re-contact the server and then simply gzuncompress() using PHP.

Example:

const decompressString = async (compressedString) => {

  const decompressionScriptFilepath = '/decompress-string.php';
  const compressedStringToSend = { method: 'POST', body: compressedString };
  const response = await fetch(decompressionScriptFilepath, compressedStringToSend);

  return await response.text();
}

PHP Script at /decompress-string.php

<?php

  $Compressed_String = file_get_contents('php://input');
  $decompressedString = gzuncompress($Compressed_String);
  echo $decompressedString;

?>

Then you simply need to invoke the javascript function:

decompressString('eNoLycgsVgCiRIWS1OISPYWQUf4of5Q/yh/lj/JH+aP8wc0HAERY4KM=');
Rounin
  • 27,134
  • 9
  • 83
  • 108