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!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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':

1
2
3
4
5
6
7
8
9
10
11
12
13
<?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

Share on FacebookShare on Google+Share on StumbleUponTweet about this on TwitterEmail this to someone

Facebook comments:

You can skip to the end and leave a response. Pinging is currently not allowed.

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

  1. avatarnuthman says:

    Oh, well if it’s just a string, then it should work perfectly fine. Pulling strings from a database is exactly what I use this script for. Here is an example of pulling player data for a game from a mysql table that would work with my script:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    <?php
    // Connect to your database
    $connection = mysql_connect("localhost","myDB","password");
    $selectedDB = mysql_select_db('myDB', $connection);
    session_start();

    // Get email of current player from session
    $email = $_SESSION['Email'];

    // Get player info
    $playerData = mysql_query("SELECT * FROM Player WHERE Email = '".$email."'");

    if($playerData){
        // Get basic player information
        $row = mysql_fetch_array($playerData);
        $displayName = $row['Alias'];
        $fname = $row['FirstName'];
        $lname = $row['LastName'];

        // Put it all together and send it back to Flash
        $returnVars = array();
        $returnVars['success'] = true;
        $returnVars['displayName'] = $displayName;
        $returnVars['fname'] = $fname;
        $returnVars['lname'] = $lname;
        $returnVars['email'] = $email;
        $returnString = http_build_query($returnVars);
        echo $returnString;
    }
    else{
        // There was no data on that email address. success = false
        $returnVars = array();
        $returnVars['success'] = false;
        $returnString = http_build_query($returnVars);
        echo $returnString;
    }

    // Keep in mind that flash will receive true / flash as 0 / 1 from PHP
    ?>
  2. avatarRicardo says:

    I keep receiving error #2101 (The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.) after a simple echo like this:

    echo “result=success”;

    What can it be ?

    • avatarnuthman says:

      Hello Ricardo,

      That error means that Flash did not receive the variables in a proper ‘format’, ie URL-encoded query string.

      You have to make sure that you build the query string properly. If you have a variable named $success that you want to return to flash, you should put it together properly:

      $success = “1”;
      $returnVars = array();
      $returnVars['success'] = $success;
      $returnString = http_build_query($returnVars);
      echo $returnString;

      also, open make sure there are no errors in your php file (and also that the php file is located on a php enabled server). test your file out in a browser to make sure that it returns no errors: http://yoursite.com/yourphp.php

  3. avatarJoey says:

    Awesome! thank you!

    -Joey

  4. avatarJoey (again) says:

    Hey, your example seems to work but all im trying to do is display the score and playername in the html file, how do i do that?

Leave a Reply

You must be logged in to post a comment.