Is your string zipped?

While looking into a strange issue on a multisite WordPress installation which optimized the pages of the main but not of the sub-blogs, I needed code to check whether a string was gzipped or not. I found this like-a-boss code-snippet on StackOverflow which worked for gzencoded strings:

$is_gzip = 0 === mb_strpos($mystery_string , "\x1f" . "\x8b" . "\x08");

But this does not work for strings compressed with gzcompress or gzdeflate, which don’t have the GZIP header data, so in the end I came up with this less funky function which somewhat brutally simply tries to gzuncompress and gzinflate the string:

function isGzipped($in) {
  if (mb_strpos($in , "\x1f" . "\x8b" . "\x08")===0) {
    return true;
  } else if (@gzuncompress($in)!==false) {
    return true;
  } else if (@gzinflate($in)!==false) {
    return true;
  } else {
    return false;
  }
}

Klunky, but it works. Now if only this would confirm my “educated guess” that the original problem was due to a compressed string.

1 thought on “Is your string zipped?”

  1. I just want to note a) I’m very grateful to be able to use Autoptimize as a free plugin, because any other approach to what it dies would be a big hassle/impossible expense for me, and b) John Nash may be gone, but he wasn’t the only genius on Earth (you crrtainly are one)… I appreciate that you delve into the details so ably to help many web sites run cooler. You’re reducing global warming. I wish more folks would “get it.”
    Thank you!

    Reply

Leave a Reply to FJ Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.