Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compress/decompress a long query string in PHP?

Tags:

php

I doubt if this is encryption but I can't find a better phrase. I need to pass a long query string like this:

http://test.com/test.php?key=[some_very_loooooooooooooooooooooooong_query_string] 

The query string contains NO sensitive information so I'm not really concerned about security in this case. It's just...well, too long and ugly. Is there a library function that can let me encode/encrypt/compress the query string into something similar to the result of a md5() (similar as in, always a 32 character string), but decode/decrypt/decompress-able?

like image 972
jodeci Avatar asked Jun 08 '10 09:06

jodeci


1 Answers

You could try a combination of gzdeflate (raw deflate format) to compress your data and base64_encode to use only those characters that are allowed without Percent-encoding (additionally exchange the characters + and / by - and _):

$output = rtrim(strtr(base64_encode(gzdeflate($input, 9)), '+/', '-_'), '='); 

And the reverse:

$output = gzinflate(base64_decode(strtr($input, '-_', '+/'))); 

Here is an example:

$input = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';  // percent-encoding on plain text var_dump(urlencode($input));  // deflated input $output = rtrim(strtr(base64_encode(gzdeflate($input, 9)), '+/', '-_'), '='); var_dump($output); 

The savings in this case is about 23%. But the actual efficiency of this compression precedure depends on the data you are using.

like image 127
Gumbo Avatar answered Sep 16 '22 16:09

Gumbo