Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to test if a string is gzdeflated?

That is to say, a test for whether or not I can safely gzinflate the string.

If my compressed data has been tampered with I get a "bad data" warning. I don't want to suppress the warning which means I either have to trap it, or test that it can be gzinflated. The latter is my preferred solution but I just don't know how.

Something to fit the code sample below would be perfect:

if(i_can_haz_inflate($data))
{
    // go ahead
    $source = gzinflate($data);
}
else
{
    // bad data
}

Edit: Having specified gz(de|in)flate I've come to realize that I'm not actually too bothered about the compression algorithm. Are there any out there that are better suited to checking the integrity prior to a decompression attempt?

like image 390
Matthew Avatar asked Jan 17 '13 11:01

Matthew


2 Answers

gzinflate() returns the original string if it's not a gzdeflate() encoded string.

The most obvious check would be:

$deflated = @gzinflate($data); // to avoid getting a warning
if ($data != $deflated && $deflated !== FALSE) {
     $source  = gzinflate($data);
}

I don't think there's another way to do this.

like image 81
Vlad Preda Avatar answered Oct 30 '22 13:10

Vlad Preda


I'm agree with @Vlad Preda answer, but we can convert warning to exception:

set_error_handler(function ($code, $description) {
    throw new \RuntimeException($description, $code);
});
$deflated = gzinflate($data);
restore_error_handler();

and it provides for us ability to handle exception... and don't suppress warnings...

like image 21
cn007b Avatar answered Oct 30 '22 11:10

cn007b