User Tools

Site Tools


I wanted to make saving session variables to a mySQL database a little sexier. I didn't like the way I've seen some programmers making a column for every single array key. It seemed inefficient to me, and I would rather just save the whole array, and recall it again whenever I want it.

Therefore, I created compress() and expand(). Really, really simple stuff; but it works and does what I wanted.

Important Information

It should be noted that these functions are for usability only, to allow the passing of an entire array to (for example) a database, a flat file, or even a script on another server (for example, compress($_SESSION) to send the entire session cookie). However, this is not a “secured” function; the data is not readable to the naked eye in its compressed format, but it is easily uncompressed, and no security measures are taken to prevent this (as that is not my intention with this script).

Also, please note that the use of the words “compress” and “expand” are in terms of the layout of the array, not the size in bytes. A compressed array using this method will in fact be slightly larger than the original array, in bytes, but will be one string as opposed to multiple array keys and values.


To use compress() or expand(), take your array $myarray and send it through the function.

Compress your array, converting it to a string: $myarray = compress($myarray);

Expand your array, converting it back to an array: $myarray = expand($myarray);

Or, you can save your entire array, with all its keys and values, directly to your mySQL database with a command such as:

$output = mysql_query(“INSERT INTO mytable (mytablecolumn) VALUES('compress($myarray))') ”); (*UNTESTED)

Source Code:

// compress/expand functions to turn arrays into unreadable compressed doodles by Robbie
// not a secure thing, just makes saving an entire array to database a lot nicer
function compress($thisVar) {
 $thisVar = serialize($thisVar);
 $thisVar = gzcompress($thisVar, 9);
 $thisVar = base64_encode($thisVar);
 return $thisVar;
function expand($thisVar) {
 $thisVar = base64_decode($thisVar);
 $thisVar = gzuncompress($thisVar);
 $thisVar = unserialize($thisVar);
 return $thisVar;
web_development/compress_expand_functions.txt · Last modified: 2012/01/26 08:57 by import