flash and php – Send/Receive Variables from Actionscript 3 & PHP

Below is a class that I made that can be used to send a group of variables to a php script on a server and receive the results. I use this all the time when working between flash and php in my projects!

// FlashPHP Class by Rick Nuthman
// 8.28.09
// Constructor receives 2 arguments:
// url:String - The url to the PHP file
// flashVars:Object - An object that contains variables to be sent to the url
//
// The class dispatches 1 event called "ready" once the php transaction is complete.
// listen for this event. Once it's received you can access returned variabled from receievedVars.

package com.frigidfish{

    import flash.net.URLVariables;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.net.URLLoaderDataFormat;
    import flash.net.URLRequestMethod;
    import flash.events.EventDispatcher;
    import flash.events.Event;

    public class FlashPHP extends EventDispatcher {
       
        // Public Properties
        public var receivedVars:URLVariables;      
       
        // Private Properties
        private var url:String;    
        private var flashVars:Object;
        private var request:URLRequest;
       
        private var completeEvent:Event              = new Event("ready");
        private var variables:URLVariables           = new URLVariables();
        private var loader:URLLoader                 = new URLLoader();

        public function FlashPHP(url:String, flashVars:Object) {
           
            this.flashVars                      = flashVars;
            this.url                            = url+"?r="+ new Date().getTime();
           
            parseVariables();
        }

        // Private Methods
        private function parseVariables() {
           
            for (var item in flashVars) {
               
                variables[item] = flashVars[item];             
            }
           
            sendVariables();
        }

        private function sendVariables() {
           
            request                                 = new URLRequest(url);
            request.method                          = URLRequestMethod.POST;
            request.data                            = variables;
           
            loader.dataFormat                       = URLLoaderDataFormat.VARIABLES;           
            loader.addEventListener(Event.COMPLETE, variablesAreLoaded);
            loader.load(request);
        }

        function variablesAreLoaded(event:Event) {
           
            receivedVars                            = new URLVariables(loader.data);
            dispatchEvent(completeEvent);          
        }
    }
}

Here is an example of how to implement it:

import com.frigidfish.FlashPHP;
var score:String = "100";
var playerName:String = "Bobby";
var phpData:*;

var playerObject:Object = new Object();
playerObject.score = score;
playerObject.playerName = playerName;

var flashPHP:FlashPHP = new FlashPHP("http://www.yoursite.com/yourphp.php", playerObject);
flashPHP.addEventListener("ready", processPHPVars);

function processPHPVars(event:Event){
// put the object that php sends back into a var (in this case phpData)

phpData = event.target.receivedVars;
trace(phpData.success);
}

Of course it will be necessary to know what to do with the data on the PHP side… here is a simple script that receives that variables and sends back a simple response var called ‘success’:

<?php
$teamName = $_POST['playerName'];
$score = $_POST['score'];
// Here you would put any processing functions...
//...

$success = "1";
//...
$returnVars = array();
$returnVars['success'] = $success;
$returnString = http_build_query($returnVars);
echo $returnString;
?>

Basically, this script does nothing with the variables that are collected, but as you can see, it just takes what is posted from flash and assigns it to php variables. Lastly, we create a new array to contain any vars that will be sent back to flash. This array is converted into a query string which is translated by FlashPHP into an object containing the variables by key names created in PHP.

I hope this makes sense, it’s actually quite easy to use! Don’t forget to wait for the FlashPHP “ready” event to trigger before attempting to access its receivedvars property. Feel free to ask any questions if anything doesn’t make sense ๐Ÿ™‚

Download Example

58 thoughts on “flash and php – Send/Receive Variables from Actionscript 3 & PHP”

  1. Flash Video Stream Tool enables you to quickly upload Flash-Videos and attract more of your Site’s visitors to buy/download/subscribe. Now that you know more about this technology it is advised to test it live so you could truly experience how it can improve the performance of your marketing efforts.

  2. Heya, I have been trying to get something like this to work for weeks now. I will try to explain exactly what I have done and mayhaps you can help me out.

    I copied the code directly off of this site. The FLASHPHP class script exists in com/frigidfish. The flash movie exists in the root of com. The php file exists in the same root as the flash movie.

    When I compile the flash movie it compiles without error and traces undefined.

    I am running off of localhost and modified the respective line to
    var flashPHP:FlashPHP = new FlashPHP(“http://localhost/test.php”, playerObject);

    Thanks in advance.

  3. Upon further testing if i modify the line
    trace(phpData.success);

    to read
    trace(phpData);
    it will spit out a ton of unformatted data which includes the success variable.

    %3Cbr%20%2F%3E%0A%3Cb%3ENotice%3C%2Fb%3E%3A%20%20Undefined%20index%3A%20teamName%20in%20%3Cb%3EC%3A%5Cweb%5Cwamp%5Cwww%5Ctest%2Ephp%3C%2Fb%3E%20on%20line%20%3Cb%3E3%3C%2Fb%3E%3Cbr%20%2F%3E%0Asuccess=1

    I hope this helps.

  4. and upon even further testing if i remove the first two lines of code in the php file it works fine. i.e. output from flash movie = 1.

    open php
    //$teamName = $_POST[‘teamName’];
    //$score = $_POST[‘score’];
    $success = “1”;
    $returnVars = array();
    $returnVars[‘success’] = $success;
    $returnString = http_build_query($returnVars);
    echo $returnString;
    close php

    of course this removes my writing functionality but allows for read functionality.
    Again any help would be appreciated.

  5. Hah! Good catch. Strange thing though, while you were researching this I compiled a test project (just copied and pasted the code from this post into actual files) and I attached it to the post. I ran it and it didn’t throw any errors..

    It must have some sort of ‘strict’ mode that is turned off. I will make the correction in the post, thanks!

  6. Nice post. I’m looking around for new ideas for my free web arcade game sites and I found this blog. I believe that with HTM5, there will be an upheaval of the current market even if actionscript will maintain its current share IMHO, as well as traditional games on optical media (PC Games etc..)

  7. Hey thanks for this class, unfortunately it hasn’t fixed my problems just yet. I keep getting this error:

    ————–

    Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
    at Error$/throwError()
    at flash.net::URLVariables/decode()
    at flash.net::URLVariables()
    at flash.net::URLLoader/onComplete()

    ————–

    I have removed the GET value that the class adds which holds the date. (?r= new Date().getTime()) which gave me this error:

    ————–

    Error #2044: Unhandled ioError:. text=Error #2032: Stream Error. URL: file:///C|/wamp/www/FlashPHP%5FTest/connector.php?r=1274179190220
    at data::FlashPHP()
    at FlashPHPTest_fla::MainTimeline/handleSubmitClick()

    —————

    Here’s my AS3 code:

    —————

    import flash.net.*;
    import data.FlashPHP;

    var newacct:Boolean = newacct_mc.selected;
    var loader:URLLoader = new URLLoader();

    function handleCheckClick(event:MouseEvent) {
    if(newacct_mc.selected == true) {
    newacct_mc.label = “Please enter your desired username and password”;
    newacct = true;
    submit_mc.label = “Create Account”;
    } else {
    newacct_mc.label = “Or don’t you have an account?”;
    submit_mc.label = “Login”;
    newacct = false;
    }
    }

    function regProcess(event:Event) {
    var returnedVars = event.target.recievedVars;
    status_txt.text = returnedVars.status;
    var checkReg = returnedVars.checkReg;
    }

    function handleSubmitClick(event:MouseEvent) {
    if(newacct == true) {
    status_txt.text = “Attempting registration… Please wait.”;
    var varsObj:Object = new Object();
    varsObj.mode = “reg”;
    varsObj.name = login_mc.name_txt.text;
    varsObj.pass = login_mc.pass_txt.text;
    var flashPHP:FlashPHP = new FlashPHP(“connector.php”, varsObj);
    flashPHP.addEventListener(“ready”, regProcess);
    } else {
    status_txt.text = “Attempting to login… Please wait.”;
    }
    }

    newacct_mc.addEventListener(MouseEvent.CLICK, handleCheckClick);
    submit_mc.addEventListener(MouseEvent.CLICK, handleSubmitClick);

    —————

    And here’s my PHP code:

    —————

    require_once(“include.php”);

    $connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
    $selection = mysql_select_db(DB_NAME);

    $vars = array();
    $vars[“status”] = “Registration failed.”;
    echo http_build_query($vars);

    —————-

    If you could help me out here that would great. Thanks!

  8. Hello Michael! Thanks for stopping by.

    Error #2101 means that whatever was sent back from PHP was not a valid query string. It is possible that you are using php4 rather than php5..

    Try navigating to your php file via a web browser and see if it generates an error..

  9. Thanks for getting back to me.

    Yeah I guessed that’s what the error meant, but I’ve checked what php sends back.

    I’m using php5.3 and I have already checked it in the browser, it comes back as a perfect (as far as I know) query string. Which is…

    status=Registration+failed.

    And if you’re wondering I’ve already tried this urlencoding values and it still says the same thing.

  10. Michael:

    So I tried to test out your php by doing a quick test, here is what I did in flash:

    import com.frigidfish.FlashPHP;
    import flash.events.Event;

    var test:FlashPHP = new FlashPHP("http://localhost/test.php");

    test.addEventListener(test.READY, go);

    function go(event:Event):void{
        trace(event.target.receivedVars.status);
    }

    and here is what I did in php (of course I left out the SQL stuff:

    Now this traced out: Registration failed

    I’ve also looked at your actionscript and I can’t see anything wrong..

    Since my test worked, can you try something for me. Could you copy my AS3 and PHP from the example above, and test it on your server just to be sure its not something else weird?

  11. Hey it worked! I had to change to things however.

    1. I had to create an empty object to send to the class as it is required. Here’s the code:

    ———–

    var obj:Object = new Object();
    var test:FlashPHP = new FlashPHP(“http://localhost/test.php”, obj);

    ———–

    2. And I had change the event listener to the what is it below:

    ———–

    test.addEventListener(“ready”, go);

    ———–

    I’ll check this out a bit later and see what the differences are between yours and mine.

    Just as a note, I’m also attempting to use something called AMFPHP (you’ve probably heard of it), people say it makes connecting Flash and PHP really easy. I’m still having trouble making it work, but if I can get it to work it’ll be much more powerful then sending back query strings and all that.

  12. Oh, sorry about that… I forgot that my local copy of FlashPHP has been updated to not require an object from flash (if php doesn’t expect variables.) Here it is in case you want it below.

    Yeah, I have heard of AMFPHP. I actually started looking in to it and it seems pretty useful. Actually, on a new project that I am working on, I have started researching Flash Builder 4. It actually can automatically generate a lot of php services and handles all of the communication between flex/flash and php. Check out this short 5 video series on youtube:

    http://www.youtube.com/watch?v=x-Da1SD1Ykk&feature=related

    and here is the updated FlashPHP class:

    // FlashPHP Class by Rick Nuthman
    // 8.28.09 (updated 4.02.10)
    // Constructor receives 2 arguments:
    // url:String - The url to the PHP file
    // gameVariables:Object - An object that contains variables to be sent to the url
    //
    // The class dispatches 1 event called "ready" (FlashPHP.READY) once the php transaction is complete.
    // listen for this event. Once it's received you can access returned variabled from receievedVars.

    package com.frigidfish{

            import flash.net.URLVariables;
            import flash.net.URLLoader;
            import flash.net.URLRequest;
            import flash.net.URLLoaderDataFormat;
            import flash.net.URLRequestMethod;     
            import flash.events.EventDispatcher;
            import flash.events.Event;

            public class FlashPHP extends EventDispatcher {
                   
                    public var receivedVars:URLVariables;              
                    public var READY:String = "ready";              

                    public function FlashPHP(url:String, vars:Object = null) {

                            if(!vars) vars  = new Object();                      
                            parseVariables(vars,url+"?randomsignature="+ new Date().getTime());
                    }
                   
                    private function parseVariables(object:Object,url:String) {
                       
                            var urlVars:URLVariables = new URLVariables();
                            for (var i in object) urlVars[i] = object[i];                      
                            sendVariables(urlVars,url);
                    }

                    private function sendVariables(urlVars:URLVariables,url:String) {
                        try{      
                            var loader:URLLoader    = new URLLoader();
                            var request:URLRequest  = new URLRequest(url);
                            request.method          = URLRequestMethod.POST;
                            request.data            = urlVars;
                            loader.dataFormat       = URLLoaderDataFormat.VARIABLES;
                            loader.addEventListener(Event.COMPLETE, process);
                            loader.load(request);
                        }
                        catch(error:Error){
                            trace(error);
                        }
                    }

                    private function process(event:Event) {                    
                            receivedVars            = new URLVariables(event.target.data);
                            dispatchEvent(new Event(READY));                           
                    }
            }
    }
  13. Ah ok, lol.

    Ok. It does seem pretty useful; just hope I can get it to work.

    Yeah I watched most of the series you linked to, looks like Flash Builder might be a life saver in these situations. Sometime soon I plan on upgrading to CS5, so I’ll be getting then.

  14. Hey! I got it AMFPHP working! I’ve built a little application that handles user accounts and changes depending on the information that it gets from the database (like whether modules show up etc). The main problems were in my PHP; AS3 (or AMFPHP, one or the other) seems very picky about how the PHP is structured. But anyway, it’s all good now ๐Ÿ˜€

  15. cool! I’ve come to the conclusion that Object Oriented PHP is the future for these types of transactions. It is so much easier to tell what is going on when you can directly call functions in PHP with specific tasks. You should write a tutorial on how to make a login system using AMFPHP. I made you an author in case you ever would like to write about it. I am trying to encourage people to write easy to follow tutorials on here that people can use to get started.

  16. err. This might sound like a daft question. And I have looked on the net I promise, but it appears this knowledge is assumed. WHERE do you put the package file so that it can be imported?

    Thanks

  17. Hey sorry I haven’t been on here in ages. Just thought I’d let you know about my progress with AMFPHP. And oh you’ve made me an author? Awesome. I’ll post a tutorial on how to use my AMFPHPConnection class.

    My progress with AMFPHP has gone great, I’ve made an over 20 video tutorial series on youtube about it. You can watch the series here: http://www.youtube.com/user/BlackBulletIV#grid/user/CAD2DAE46A04939D

    I’ve also made a class that greatly eases and enhances using AMFPHP, which is called AMFPHPConnection. You can download it and view instructions here: http://www.nova-fusion.com/cms/index.php?option=com_content&view=article&id=44:amfphpconnection&catid=17:actionscript&Itemid=59

    I might post the instructions and class as a post here as well, since you want me to post some stuff. Anyway, best of luck! ๐Ÿ™‚

  18. Thanks ๐Ÿ™‚ I think I may do a several part series on making a log in system with AMFPHP. Not sure I’ll do anything much on introductory topics to do with AMFPHP, I’ve already done a video series on that stuff.

  19. Hey guys, how do call values from a TextInput VS a defined string?

    For example, using the code above:

    var playerName:String = playerName_txt.text;

    var playerObject:Object = new Object();
    playerObject.playerName = playerName;

    ORIGINAL:

    var score:String = “100”;
    var playerName:String = “Bobby”;
    var phpData:*;

    var playerObject:Object = new Object();
    playerObject.score = score;
    playerObject.playerName = playerName;

    ~

    I’ve read around the net for several days now and have gotten nowhere.. any help would be appreciated.. thanks guys!

  20. Hey there, Nuthman..

    I’m getting absolutely no error messages, just a blank response.

    When tracing (ex: score) I get nothing. No undefined, etc.

    ~

    However, if I define var score:String = “100”; everything works perfectly fine… it just refuses to return a TextInput value.

  21. That’s weird..

    So let me make sure I understand correctly. Is it when you try to read the score ‘back’ from PHP that you are getting the blank variable?

    It sounds to me like you are posting the variables to PHP before your text box is being populated. Is that a possibility?

  22. Unfortunately this problem occurs prior to submission to PHP. Even when “tracing” var score (score_txt.text) directly below defining the score var, absolutely nothing is returned. No error messages or anything.. just completely blank. I’m mind boggled and feeling exhausted over it.

    Back to PHP though, that is the root problem… trying to post the var… if Flash won’t recognize the data, surely PHP receives nothingness as well.

    With this problem aside, I love your scripting above btw.. meant to thank you in the opening post.

    Just with what I’m trying to do, read/carry data from a TextInput VS a string, I’m rendered stuck until figuring this out. (4 days now)

    ~

    A secondary thing I’m trying to figure out, being new at this, how would one go about “calling”/using the received VarString from PHP within other frames or outside of said function even, without calling the function to post/receive vars every time?

    I’ve read about classes/public vars, and am admittedly confused like no other. AS3 seems to be quite the picky little bugger so far, but I’m trying my best to learn it.

    Thanks again for trying to help here, I really appreciate your time and insight.

    – Dev

  23. Dev –

    Would you mind either pasting all of your code, or email me your project to take a look?

    I’m swamped with work right now, but later I’ll post an example using a text box, and I’ll use the variables from different locations.

  24. Thanks again to the Demigod of code!

    Everything is working beautifully… although, with all the knowledge you’ve shared, you may have created a demon with all these crazy new possibilities flowing within! =P

    – Dev

  25. Hi!
    thank you very much for all the support!
    One question: is it possible to pass a variable (i.e. $test) to the $success and not just a simple string.
    I am asking that because when I try to pass a variable I get the error
    Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.

    Thank you so much!!

Leave a Reply