Using ActionScript 3.0 with PHP Part 1: Loading External Variables
Creating dynamic websites which combine the power of Flash or Flex with PHP is easier than ever with ActionScript 3.0.. Utilizing the networking power of the Flash player we can create next-generation user interfaces which go well beyond static web pages or simple animations and instead act as the front-end for powerful applications. These applications can interface with databases and web services, giving us the ability to add new features, create ‘mash-ups’, or previously unheard-of platforms for user interaction. The sky is the limit! So let’s get started.
Server Requirements
If you are creating web applications which run Flash and PHP obviously your server needs to have PHP installed. If you plan on creating many dynamic sites or applications going forward, you will probably want server space which allows for unlimited databases, has PHP5 and MySQL, and gives you the ability to install programs on the web server. If you are using shared hosting, that is fine, but keep in mind that you will probably want to go with a Virtual Dedicated solution at some point, simply because of the flexibility and responsiveness you receive from having your “own” server. For a virtual dedicated server I personally use GoDaddy, (see my article here about VDS), as I now have unlimited domains, unlimited databases, and root access to my server, so I can do a bit of shell scripting now and again. On top of that it is super-responsive which is really important for creating Flash applications which utilize networking. Otherwise if you want to pay less but still want unlimited domains and a fairly responsive system, I would go with Blue Host in North America or 1 and 1 for Europe (or other regions), and a shared hosting plan. I have experience with all three of these companies and the support is certainly top-notch.
Communicating with a Web Server
Let’s discuss three ways in which we might send data back and forth between a web server and Flash. These are by no means the only ways to do so, but they are fairly common, and you will find them to be popular ways to accomplish networking tasks.
Using GET or POST and Variables
If you are used to working with HTML front-ends and PHP (or another scripting language), this will be familiar to you. Using the GET or POST method, you can send and receive data from server-side scripts. In this scenario, we often output our data in some sort of url-encoded string, which contains variable “name and value” pairs. This is the method we will cover in this article.
Using XML
XML is one of the most important languages for communication between application, servers, and services on the Internet. One good reason to work with XML for loading data from a web server is that you will generally not have to know how the data is being processed, you will just have to know something about the particular XML formatting being used, so that you can process the data.
Using Flash Remoting
For more sophisticated integration with a server, you may want to utilize Flash remoting. If you are using Flex, you may work with Flex Data Services. If you would like an open-source solution, you might want to look into AMFPHP. We will not cover Flash remoting in this series.
Loading Variables
The first thing we will do is use GET to load variables from a PHP script. We will create a simple PHP document, called “dataLayer.php”. This page will act as our main communicator between our server and Flash.
File: dataLayer.php
<?php
$returnVars = array(); $returnVars['username'] = "John Doe"; $returnVars['email'] = "johndoe@hotmail.com"; $returnString = http_build_query($returnVars); //send variables back to Flash echo $returnString; ?>
So here we have our data layer. It consists of two variables: username and email. These variables are encoded using the http_build_query() function to send a properly formatted, compliant variable set from the server. Notice that this function takes an array as a parameter. It then just builds out of string in the format of name / value pairs, like so “varname=value&varname2=value”. It’s very handy.
Next, we will instruct the Flash player to load this data so that we can work with it.
Loading the Variables into Flash
Now let’s write some ActionScript to load our variables into Flash. We will do this in a document class which will be the main point of entry for our Flash movie. (If you are not familiar with the document class, see my tutorial here). Our document class will be called “Main.as” and we will utilize it with an .fla file called “main.fla”.
Complete Main.as code below. You can also download it here: data-loader.zip
package {
import flash.display.MovieClip;
import flash.events.*;
import flash.net.*;
public class Main extends MovieClip {
public function Main() {
// Prepare request
var request:URLRequest = new URLRequest("http://www.yourserver.com/dataLayer.php");
request.method = URLRequestMethod.GET;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, completeHandler);
loader.load(request);
function completeHandler(evt:Event) {
var username = evt.target.data.username;
var email = evt.target.data.email;
trace ('username is ' + username);
trace ('email is ' + email);
}
}
}
}
You will want to replace the path (”http://www.yourserver.com/”) with your actual server and directory.
This code is very simple. You will see that we have imported appropriate classes for working with networking, and that our class (being the document class) extends MovieClip.
The first part of our constructor class prepares a request, and it uses the GET method to do so. Here we make an instance of the URLRequest object, passing it the actual web path to our php file.
var request:URLRequest = new URLRequest("http://www.yourserver.com/dataLayer.php");
request.method = URLRequestMethod.GET;
We then make a URLLoader object, specifying its dataFormat property to be “VARIABLES”. This will ensure that we can bring the variables output by PHP into Flash using the same names, and those variables can easily integrate into the scope of our Flash movie.
var loader:URLLoader = new URLLoader(); loader.dataFormat = URLLoaderDataFormat.VARIABLES;
Next we define an event handler, which is key for handling the loading of the variables. We are listening for the “COMPLETE” event, which is an event thrown by the URLLoader object that we just created. Notice that we define a handler, called completeHandler, which will do the work of processing our variables for us. This event handler will take the form of a “nested” function – a new feature in ActionScript 3 which allows us to place functions inside of functions. (I love this). After we define a handler, we then call the load() method of the URLLoader object, passing it the request objet.
loader.addEventListener(Event.COMPLETE, completeHandler); loader.load(request);
Our completeHandler() function does the work of getting our variables from the COMPLETE event. We created a parameter called “evt”, which is populated by the event object itself when this function is called. We get the variables from PHP using the “evt” object and the following syntax: “evt.target.data.variableName“. This allows us to specify the exact variable we want to access. Lastly, we trace this data to the output window.
function completeHandler(evt:Event) {
var username = evt.target.data.username;
var email = evt.target.data.email;
trace ('username is ' + username);
trace ('email is ' + email);
}
And that’s it! This is a very simple example, but it should get you going with getting data from your PHP scripts into Flash. Obviously there is a lot more to learn about communicating with a server from Flash, but in any case, AS3 makes it simple! In the next tutorial we will talk about sending and receiving data using POST. Good luck!
Tags: ActionScript 3.0, Flash and PHP, Flex, Loading data, PHP, URLLoader, URLRequest
![[image]](http://mowser.com/img?url=http%3A%2F%2Fwww.heaveninteractive.com%2Fimages%2Famazon%2F51Vo7OODj6L._SL160_.jpg)
Comments(16)
I have gathered important information out of this blog. I think this information is pretty much useful for a Web developer.
well,
i always get the same error ..
Error opening URL ‘%url%’
Error #2044: Unhandled ioError:. text=Error #2032: Stream Error. URL: http://localhost/www.ebaai.de/tmp.php
at TryLoadvars$iinit()
at flash.display::Sprite/flash.display:Sprite::constructChildren()
at flash.display::Sprite$iinit()
at flash.display::MovieClip$iinit()
i attach an actionscript class in flash cs 3, and i never can use url request, why?
hey there. i’m trying to get as3 & php running but seems like i’m doing something wrong – when I run your code locally and trace evt.target.data i get:
seems like the php returns the text of the php in some weird format.. any ideas what’s causing this? tried searching online but nothing… thanks for the great info on this post!
hm sorry the trace didn’t go through, probably a security thing, it looks like:
“<?php
$” and then goes the rest of the php file text in similar encoding…
m, disregard – my php wasn’t turned on
got it going, thanx for the great post
Fine, thanks for the tutorial.
It works but flash won’t retrieve the first entry of the array.
This is because the output is name=”yourname”&email=”youemail”. On my trials I could not retrieve name and the reason was the missing “&” symbol in the string generated by http_build_query.
In that case my simple solution was to initiate the array with some useless data, like:
nada=nada&name=”youname”&email=”youremail:)
hey I tried the tutorial but i only get a everything on the 1st variable and undefined on the 2nd variable.
Hi,
I get this error:
Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
Any ideas??
I already had the same problem with the error message above. To solve it I just changed the VARIABLES, from the code, to TEXT. The compiler showed none error message now. Good blog, however I found some problems in implementing the code above, probably because I just started programming in AS3, I will trying a little harder.
Hi there,
Nice tutorial. Have you created part 2 yet? Im very interested in learning how to interact with php/mysql/xml and Flash.
Vic,
I was getting the same problem – turned out that I had php 4.x on my hosting and the http_build_query isn’t in that version, so the output was throwing an error in php that confused the hell out of flash…
Change loader.dataFormat = URLLoaderDataFormat.VARIABLES;
To // loader.dataFormat = URLLoaderDataFormat.VARIABLES;
And put trace(evt.target.data); into the completeHandler and you will be able to see the output from the php file (or you could look at the php file in a web browser)…
It’s working fine now the PHP has been upgraded, but didn’t seem to get it working in other ways…
Hope this helps
PS: Also had a problem where the PHP output file was being cached – watch out for that when making changes…

This tutorial was very helpful and I finally after many days got the php file to be seen by flash. When I do a trace statement all of the data shows up, but when I try to display the data only one line of the data displays and it’s not the right data. Example the wrong last name is displayed next to the first name. If anyone can help me with this I will love you forever!
I am making progress. I have all the data now and in the right places – the only problem is that the data for each column is on the same line separated with commas. How do I get them to show up on separate lines? I tried adding \n to the php script, but that didn’t work. I’m not sure how I would accomplish that in ActionScript 3.
Thanks for this short tutorial, I didn’t knew the power of URLRequest and URLLoader.
This is really to communicate between AS and PHP, just an echo, thought it would more difficult.
Thanks again!
I am having a problem using http_build_query. I get the first variable but that is all. Every other variable is undefined. If I format the return string from php as follows
$returnVars = “username=John Doe”;
$returnVars .= “&email=hotmail.com”;
echo $returnVars;
No problem. However if you put the ampersand in the first name value pairing as follows:
The following error occurs in flash:
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 Fetch_fla::MainTimeline/handleComplete()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()
If you examine the output of the example there is no ampersand on the first variable so flash should trace out both variables but I always get undefined for the second one.
Any one know why? Has anyone found a solution? I am running php 5.2.4 so there should be no problem with the php. I am going crazy. I can’t say if you help me that I will love you for ever but you would make a grown man cry.
Thanks for any help.
imailjim@gmail.com
Jim
Hi Jim
I had a similar problem once, I think it had to do with putting the ampersand in front of the return string.
My advice is to try both methods:
1) to echo “&firstValue&secondValue”
and
2) to echo “firstValue&secondValue”
One of these is right, and one is wrong, I’m not sure which. It’s a flash quirk I believe. (One of many).