Serialize + base64_encode an array for a URL

Posted on: Apr 08, 2008 by wenbert

This is an alternative for passing a bunch of variables in the URL. The variables might be used for pagination scripts (limits, etc.), sorting results and others. Generally, I would do something like this for sorting results:

http://localhost/reports?sort=username&sort_type=ASC

That will work fine in most cases, but what if you had tons of variables to pass to the URL? Using POST would be out of the question since I would want that URL to be “bookmark-able”. So the answer would be serialize() and base64_encode().
I would do something like this:

//In this example, I am using Zend Framework. The code below is found in my Controller file.
$myOptions = array();
$myOptions['sort_by'] = 'username';
$myOptions['display_images'] = 'yes';
$myOptions['edittable_fields'] = 'no';
$x = base64_encode(serialize($myOptions));
$this->_redirect('/report?q='.$x);

On the “receiving” end of the applications — the View file, I would do something like this:

if(isset($_GET['q'])) {
    $q = unserialize(base64_decode($_GET['q'])); //this reverses the serialize() and base64_encode()
}
Zend_Debug::Dump($q); //This would output the same array (found in the Controller file) with the values included.

This is useful in many other scenarios. And this is just one way of doing it — pretty dirty in my own opinion but the serialize() + base64_encode() method has saved my neck more than once.

If you have a better solution, then please post a comment below. ;)


Subscribe to comments Comment | Trackback |
Post Tags: , , ,

Browse Timeline


Comments ( 2 )

You want a better way… what about this.

I’m thinking on the fly here. Why not save the data you are serializing in to a database (serialized form) & put a unique key on the field in the database to prevent duplicate entries… then use something like: website.com/?url_id=452

This looks up in the database the URL parameters you need to use, gets the URL from the database, unserialize it… and walla! You got all your variables you need and a very nice short URL for bookmarking that could even be improved using mod_rewrite ;-)

Feel free to email me your opinions on this technique.

Kind regards,
Scott

Scott added these pithy words on Apr 24 08 at 8:11 PM

Thanks for a the different view Scott.

Wenbert added these pithy words on Apr 25 08 at 9:06 AM

Add a Comment


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">


© Copyright 2007 eKini Web Developer Blog . Thanks for visiting!