A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

Serialize + base64_encode an array for a URL

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:


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));

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. ;)

This entry was posted in General and tagged , , , . Bookmark the permalink.

2 Responses to Serialize + base64_encode an array for a URL

  1. Scott says:

    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,

  2. Wenbert says:

    Thanks for a the different view Scott.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>