ActionScript.org Flash, Flex and ActionScript Resources - http://www.actionscript.org/resources
Introduction to Flash and PHP
http://www.actionscript.org/resources/articles/141/1/Introduction-to-Flash-and-PHP/Page1.html
Neil Webb
Neil Webb is a Flash Platform Developer currently living and working in England. He joined the site when it was just a baby - look at it now! Neil has previously worked for Cambridge University, FIFA and Hutchinson Whampoa among others.
 
By Neil Webb
Published on September 9, 2005
 
Author: Neil Webb, neil AT nwebb DOT co DOT uk, http://www.nwebb.co.uk neil@nwebb.co.uk
Difficulty Level: Intermediate
Requirements: Flash MX, PHP, Apache
Assumed Knowledge: Familiarity with basic actionscript (v1)
File(s) to Download: nwjv.zip
Online Example: None

Page 1 of 5
Author: Neil Webb, http://www.nwebb.co.uk [email:neil@nwebb.co.uk]
Difficulty Level: Intermediate
Requirements: Flash MX, PHP, Apache
Assumed Knowledge: Familiarity with basic actionscript (v1)
File(s) to Download: nwjv.zip

Introduction to Flash and PHP

This is the first part of a series of tutorials looking at using PHP and Flash. In this first tutorial we're going to take things relatively easy. Over the course of the next few pages we are going to learn how to send data from Flash to PHP and back again. The basic overview is this:

Flash sends a number to the PHP script -> PHP script multiplies number by 7 and returns it to Flash -> Flash displays new number

Easy eh? Actually as you'll see it really isn't that hard, and don't worry if you've never seen a PHP script before, there's nothing complicated about the one we'll use. I can already hear some people shouting "Sure, but Flash could do this multiplication on it's own!!" - and right you are, but then that wouldn't be much of a PHP tutorial would it.

Installing PHP on your computer is the big task, and way beyond the scope of this tutorial, but never fear, there are several options available to you:

  1. If you already pay for web hosting then make enquiries with your hosting company. They do all the set-up for you. Ideally you want to be running PHP, Apache (web server) and mySQL (database) so enquire with your host about any such packages they do. The main downside of this approach is that in order to test anything you have to upload it to the remote server, and of course your hosting fee will increase. The upside is that everything you do will be available to the 'outside world'. NOTE: you could install everything on your own machine and open that up to the outside world, but unless you happen to be very knowlegable about server side stuff then that idea is quite frankly crazy-talk!!
  2. Use a preconfigured package like the excellent one at www.firepages.com.au - this makes installing PHP, Apache and mySQL on your own computer easy. You may need to read up more about installation in order to make certain tweaks to the setup, but for many this is the easiest option. The main upside is that you can test everything quickly and easily on your own machine. The main downside is that your work can't be seen by others via the web (well ...see above!)
  3. Install PHP, mySQL and Apache yourself from scratch. Use one of the many tutorials found via a search engine like Google, or from some of the excellent PHP-specific forums such as www.phpfreaks.com to guide you through the setup. The main up and downsides to this are as above.
This tutorial assumes that you have PHP and Apache running either locally or on a remote server. Everything from this point onwards is written with that assumption - no, no don't cry! If you have problems with the installation don't give up - insalling PHP may seem a little daunting, but take advantage of those PHP forums and all the lovely kind forum members just hanging around waiting to help you ;)
Do bear in mind that it is highly likely your question has been answered before, so use the forum's search facility first before posting.

Throughout this tutorial I will refer to "generating" files. If you are using a remote server this assumes that you remember to upload them to the correct directory on that server before testing. If you are running a local server it assumes you have your site structure (see below) set up in your Apache htdocs folder.

1. Before going any further we are going to set up a basic folder structure so we can keep our files organised. Mirror this structure on your remote server if you are using one and if you are running PHP and Apache locally then create this structure in your Apache/htdocs folder:

basic site structure

I called my main folder nwjv (a combination of my initials and that of Justin Vincent, a mighty PHP-weilding friend of mine). It may be best to stick with this name for now.

2. Next we're going to create a fla and set up the export options as we want them to be. So, open a fla, name it dogYears.fla and save it in the flash folder you just created. Now, within the flash file go to file -> publish settings and click on the first tab: formats .

the publish settings box for Flash MX

Make sure the flash and html boxes are ticked, then click on the folder to the right of the flash box. A popup window appears and you should navigate to the swf folder you just created, as we want to save our swf as dogYears.swf in that swf folder.
Now repeat the above process for html. All our html files are going to go directly in to the nwjv folder - I haven't created a specific folder for html.

3. Publish the movie ( file -> publish ) and check that the swf and html end up in the correct folders. They did? Excellent!


Page 2 of 5

Creating the PHP file

Don't worry about understanding the PHP right now. It will be explained in a moment. All this script does is accept a number, multiply it by 7 and print that number out to a page. We're going to use it to calculate how old we are in dog years, as one human year supposedly equals seven dog years.

4. Open up a word editor and paste in the following code:

[as]<?
$calculation= $_POST['years']*7;
echo $calculation;
?>
      [/as]

Creating the Flash file

5.On the first frame of the main timeline create a small input textbox with an instance name of years .

6. Now create a simple button and give it an instance name of myBtn .

Okay, we're cooking with gas now! First I'm going to explain what we're trying to do; The user will be able to enter their age in the input box and press the button. This sends our number to the PHP script, which will multiply it by seven. We're not going to return that number to Flash just yet. Instead we're going to print it out to an HTML page.

The reason we're doing this is because it's an excellent way for bug testing your future Flash/PHP applications. When a PHP/Flash application doesn't work it helps to know where the error lies. This method shows us what PHP is sending back, and if we can see that out PHP output is all good and proper then we know the problem will lie within the Flash part of our app.

The first thing we want to do is set up a LoadVars object (if you haven't used LoadVars before just follow the instructions below and everything should become clear in the next few steps). We'll also set up a variable called path - this has nothing to do with LoadVars. It only serves to make it easier for us to change our site folder structure in the future, if we should want to, with the minimum of hassle.

7. Add the following code to the first frame of the Flash movie:

[as]//=================================
// INIT
//=================================
path = "../nwjv/php/"; //declare path to php files
lvOut = new LoadVars(); //create lv object
[/as]

Once we have created our LoadVars object we can then create a property for it called year and store our number in there, then send the whole object to the PHP script. Reading about stuff like this before you've done it can make it sound overly complicated, so the best thing is to just do it, and then come back and re-read this paragraph to solidify in your mind what you have just done. Turn to the next page, and we'll add the code.


Page 3 of 5

8. Add the following code to the same frame:

[as]//=================================
// BTN CODE
//=================================
myBtn.onRelease = function(){
 //assign user-input value to lv property called years
 lvOut.years = years.text;
 //send to a blank window
 lvOut.send(path + "dogyears.php","_blank");
};
[/as]


In the above code we specify an onRelease event for our button. When the button is released we create a new property called years , and we assign it the value of our user input box.

Next we use the send method of our LoadVars object to send our object to whatever script we specify. The two arguments supplied are URL and TARGET. For the URL we use our path variable (which is set to equal "../nwjv/php/"), plus the name of our script (dogyears.php); and for the target we specify "_blank" which forces a new HTML browser window to open up.

Think back to the PHP script we created earlier. It uses a built in PHP function called "echo" - which does the same as "print" and prints out stuff to an HTML page. We've told it to multiply our number by 7 and then echo the result, so it should print the result of 7*year to the HTML page. Save your fla and lets try it.

REMEMBER TO DO THIS VIA LOCALHOST IF TESTING LOCALLY - ie the address in your browser bar should be something like http://localhost/nwjv/001_dogYears.html, and if you're testing on a remote server, upload your files to the relevant folders on that server.

9. Let's test this now. Once you can see the Flash interface enter a number - let's say 7 - into the input box and press the button. A new browser window should pop open, and that page should have the number 49 printed to it (7*7=49 for those that struggle with maths!) So, we know that our php script is doing its bit!

We're going to take a look at that PHP script again now:

Receiving variables from Flash

[as]<?
$calculation = $_POST['years']*7;
echo $calculation;
?>
[/as]


The "<?" is the opening PHP tag. All variables created or referenced in PHP are preceded with a dollar sign. All variables received by a PHP script are automatically stored in handy PHP arrays for us. One such array is called $_POST[] . Now, we sent a variable called years from Flash to PHP, and so using that knowledge we know we can access it like this:

[as]$_POST['years']
[/as]


As you can see from the PHP scipt, we created a variable called "calculation" and assigned to it the value of $_POST['years'] *7 , and then on the line below that we tell PHP to print that value out to the browser using the "echo" function.

Okay, now we're going to replace one line of code so that our number gets received by Flash instead of being printed out to the browser window.

10. Comment out the line echo $calculation; and replace it with the following:

[as]echo "&returnVal=$calculation";
[/as]


Again you can see that we're getting PHP to echo a value out to the page, but what about the rest of that line of code?

Well, Flash can receive data in name-value pairs (variables in the format of name=value). If there is more than one pair then each name-value pair is separated by an ampersand, and so a typical string of name-value pairs may look like this:

[as]&name1=Neil&location1=Bristol&name2=Justin&location2=London&
[/as]

The final ampersand is optional. Here we are building a name-value pair to be sent back to Flash...


Page 4 of 5

Sending variables from PHP to Flash


We've seen how variables sent from Flash can be accessed in PHP, but to send a variable back from PHP to Flash we use a slightly different method.

If Flash is expecting a value to be returned (for more info read about sendAndLoad on the next page) then it will pick up this returned value and we can use it in our Flash movie. We still use the PHP language construct echo to output our value from PHP, but we echo it in "name-value pair" format so that Flash can understand it, instead of a straight-forward variable value as we did earlier.

When sending back data from PHP to Flash it is often the case that we need to encode it properly using PHP's urlencode() method, but in this case, because we are just sending back a number it isn't necessary to encode the data in any way.

You may have also noticed that we did something in that last bit of PHP (on the previous page) that wouldn't be allow in Flash - we put a variable inside quotation marks! In PHP all variables are denoted by a dollar sign, making them easily distinguishable from normal strings. In PHP anything inbetween double quotes is evaluated. Therefore this is perfectly acceptable, and even though the variable is inside quotes it still gets evaluated:

[as]<?
$myNumber = 10;
echo "My number is $myNumber"; //prints "My number is 10"
?>
[/as]


So, putting it all together, we know we need to echo something back to flash in name-value pair format - and for the name part we're just going to chose an appropriate variable name , - "returnVal" sounds good to me! This needs to be echoed as a string. Therefore, so far we have this:

echo "&returnVal="

For the value part we want to send back our PHP variable called $calculation. We know that we can put variables inside of double quoted strings so...

echo "&returnVal=$calculation";

Viola!

Okay, we're on the home straight now. We need to go back to our Flash movie, and make a few changes so that Flash will be able to pick up and use the name value pair that we are sending back. We need to modify our actionscript code to do this. We also need somewhere to display the result.

10. Create a dynamic textbox on stage, make it multiline and wordwrap and give it the instance name of output .

11. Now replace ALL the code in frame 1 with this, and I will explain the additional code below.

[as]stop();
//=================================
// INIT
//=================================
path = "../nwjv/php/"; //declare path to php files
lvOut = new LoadVars(); //create lv object
lvIn = new LoadVars(); //create lv object
lvIn.onLoad = function (success) {
 if(success){
 //PHP variable value to textbox
 output.text = lvIn.returnVal;
 }else{
 //...or notify of failure
 output.text = "fail";
 }
}
//=================================
// BTN
//=================================
myBtn.onRelease = function(){
 //assign user-input value to lv property called years
 lvOut.years = years.text;
 //send to a blank window...
 //lvOut.send(path + "dogyears.php","_blank");
 //get results returned to lvIn
 lvOut.sendAndLoad(path + "dogyears.php", lvIn, "POST");
};

[/as]


We'll examine this code line by line starting with the INIT code. First we store our path, as a string in a variable called path . Next we create two loadVars objects. One object will be sent from Flash to PHP, and the other object receives the value sent back from PHP to Flash.

Next we use the onLoad method of our LoadVars object to tell Flash what to do if the load is successful (I've explained very similar methods in many of my other tutorials and so I will not go in to too much detail here, but basically if the sendAndLoad is successful our returnVal variable will have been sent from PHP to FLASH, and will automatically be stored inside our loadVars object called lvIn (see BTN script for more info) - and therefore we assign lvIn.returnVal to our Flash textbox. If the operation isn't successful we display a "fail" message in the textbox instead).

We'll take a look at the button code on the next page.


Page 5 of 5

As for the button code, when our button is released we take the value the user has inputted in the Flash input textbox, and add it to our [outgoing] LoadVars object as a new property. To make things easy for ourselves we decide to call the new property years .

lvOut.years = years.text;

The next line is commented out because we don't need it any more and it is the final line that does the main work!

lvOut.sendAndLoad(path + "dogyears.php", lvIn, "POST");

We use the built in sendAndLoad() method of the loadVars object to send data and receive data. Let me explain in more detail:

We use lvOut's sendAndLoad() method instead of its load() method. This allows us to send variables and get them posted back to Flash. To use sendAndLoad we need to send it three arguments; the path of our script, the LoadVars object to which we want our PHP data returned (we created it earlier - lvIn !), and our method of sending, which is "POST". At the beginning of the code you can see that I created an LoadVars object called loadIn , and we get out Flash data sent here because we specified it in the sendAndLoad() method.

We've already set up lvIn's onLoad method, so it knows what to do when data is loaded in to it. If you remember, in the PHP code we set it up to echo a name-value pair, which was basically: returnVal=$calculation;

The name-value pair is returned to Flash - the variable name becomes a property name of the lvIn instance (lvIn.returnVal), and the value gets stored in that property (so lvIn.returnVal will equal $calculation).

Blimey, did you get all that? Okay, let's have a look at the finished file first, and then I will recap over the whole thing so you can get it clear in your mind. Generate the files and upload them or whatever you need to do. Then open up dogYears.html ... (REMEMBER TO DO THIS VIA LOCALHOST IF TESTING LOCALLY - ie the address in your browser bar should be something like http://localhost/nwjv/001_dogYears.html)

... enter a number into the input box and press the button. The value of the calculation should now appear in the output textbox - you can see that the data has gone to PHP, been manipulated and then sent back and displayed in Flash!

Review of what we did

Basically, flash sends PHP a variable called "years". PHP then manipulates that variable, and echos a name-value pair (ie a variable and its value) to Flash. PHP calls the variable "returnVal". Flash then accesses returnVal from the LoadVars object it was returned to, and displays the value in a textbox.

Obviously PHP wasn't really needed for this functionality. We could have done it all in Flash with much less hassle, but this tutorial demonstrates how to get data from Flash to PHP and back again.

One last thing to note: LoadVars also has an onData method, but using both onLoad and onData at the same time causes problems and may cause the movie to cease functioning (using onData prevents onLoad from ever being called and is a know Flash bug). There are ways around this, such as explicitly calling onLoad from inside onData, but in most cases using one of the two will suffice. For now it is just something to be aware of.

Well, once again we've reached that point where I say "...and that's it for this tutorial" like it's some dodgy catch phrase. I hope it's proved a useful intorduction to PHP and Flash.

If you have any suggestions or comments about this or any of my tutorials you can email me and I will do my best to answer them. Please note that due to the volume of Flash-related emails I get, I now prioritize emails related directly to the tutorials themselves. You may find answers to your questions already posted on Flash forums such as actionscript.org and were-here.com

This, and other tutorials can be found on nwebb.co.uk