Flash "PHPLoadVars" class

I was pitching in on a forum thread Send an object to a php script the other day and some chap wanted to send complex objects to PHP using LoadVars. "Can't be done!" was the reply.

Oh yeah? Well if PHP can deserialize array variables from HTML forms, I don't see why we can't do the same with Flash.

Well it took about 15 minutes to work up a rough proof-of-concept that worked for GETs only, but it got me thinking to do something nice with:

  • a proper class
  • that works with POST (so you can send BIG objects!)
  • and has a recursive serialization routine (so you just give it any nested data-structure, and it chews through all of it)

PHPLoadVars (also works with Ruby)

Well it couldn't be simpler, really. Just create a new PHPLoadVars object, ask it to serialize your data, and send:

var data :Object      = {data:[1,2,{sub_object:{name:'Dave',age:33,gender:'male'}},3,4,5]}
var lv	 :LoadVars    = new PHPLoadVars();

Then PHP receives the complex variables natively like so (a quick print_r($_POST); shows the results):

    [data] => Array
            [0] => 1
            [1] => 2
            [2] => Array
                    [sub_object] => Array
                            [gender] => male
                            [age] => 33
                            [name] => Dave


            [3] => 3
            [4] => 4
            [5] => 5


Just to be absolutely clear – this result isn't manually de-serialized, or run through any processing routines – PHP automatically reads in data serialized using square brackets (which is how things were serialized in Flash) as numeric or associative arrays, so your data is literally ready to go as soon as the headers have been processed!

And you can make your data-structure as deep as you like…

Could it be any easier!? No. It couldn't! Not even XML is this easy!


Download the class file, sample .fla, and a basic PHP file to echo the variables to screen.


Leave a Comment