Using ActionScript 3.0 with PHP 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, 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'] = "testuser";
$returnVars['email'] = "test@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.  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!

12 thoughts on “Using ActionScript 3.0 with PHP Loading External Variables

  1. hani

    how can i pose the username and email in the .fla file? please help. i can only trace it on the output but on the exact .fla file it displays nothing. thanks.

  2. LUN

    i got the same problem, undefinded username and email…can you give me a sample about urlencoded?

    Thanks

Comments are closed.