Getting Flash CS3 talking to PHP 5 via JSON

Getting PHP5 and Flash CS3 (ActionScript 3) talking together is actually pretty easy. Borrowing some code and ideas from here I was able to craft a fairly simple example to show how you can make this work.

First, you need to go and download the as3corelib from Google Code. This gives us the ability to encode and decode JSON right in Flash (or Flex).

Make sure you have the latest PHP 5 installed (I used PHP 5.24) and ensure JSON support is available. For this example I had PHP installed on Windows XP with Apache 2.2.

Once you have the as3corelib you’ll want to copy the contents of “corelib/src” to a folder where you will be setting up your Flash project (where your gonna save the FLA and ActionScript 3 files).

Start Flash CS3 and create a new “Flash File (ActionScript 3)”. Add a new ActionScript file to this and save it as “Person.as”. Now add this code to the Person.as file:

package
{
	public class Person
	{
		public var first_name:String = "";
		public var last_name:String = "";
		public var email:String = "";
	}
}

…I know, its a bad example of a class, but this is for a demo so lets continue.

Add another ActionScript 3 file to your project and call it “URLLoaderExample.as”. Here is the code for it:

package
{
	import flash.events.*;
	import flash.net.*;
	import fl.controls.TextArea;
	import com.adobe.serialization.json.JSON;

	public class URLLoaderExample
	{
		var txt:TextArea = null;

		public function URLLoaderExample(textArea:TextArea)
		{
			var loader:URLLoader = new URLLoader();
			txt = textArea;
			configureListeners(loader);

			var request:URLRequest = new URLRequest("http://www.YOUR-PATH-HERE.com/person.php?getPerson");

			try
			{
				var header:URLRequestHeader = new URLRequestHeader("content-type", "text/plain");
				var header2:URLRequestHeader = new URLRequestHeader("pragma", "no-cache");

				request.requestHeaders.push(header);
				request.requestHeaders.push(header2);

				var per:Person = new Person();
				per.first_name = "Frank";
				per.last_name = "Smith";
				per.email = "fsmith@nowhere.com";
				request.data = escape(JSON.encode(per));

				request.method = URLRequestMethod.POST;
				loader.dataFormat = URLLoaderDataFormat.TEXT;

				loader.load(request);
			}
			catch (error:Error)
			{
				txt.htmlText = txt.htmlText + "\nUnable to load requested document.";
			}
		}		

		private function configureListeners(dispatcher:IEventDispatcher):void
		{
			dispatcher.addEventListener(Event.COMPLETE, completeHandler);
			dispatcher.addEventListener(Event.OPEN, openHandler);
			dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
			dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		}

		private function completeHandler(event:Event):void
		{
			var loader:URLLoader = URLLoader(event.target);
			txt.htmlText = txt.htmlText + "\n\n" + loader.data;

			try
			{
				var per:Object = JSON.decode(loader.data);
				for(var key:String in per)
				{
					txt.htmlText = txt.htmlText + "\nFirst Name: " + per[key].first_name;
					txt.htmlText = txt.htmlText + "\nLast Name: " + per[key].last_name;
					txt.htmlText = txt.htmlText + "\nEmail: " + per[key].email;
					txt.htmlText = txt.htmlText + "--------------------------------------";
				}
			}
			catch (error:Error)
			{
				txt.htmlText = txt.htmlText + error.toString();
			}
		}		

		private function openHandler(event:Event):void
		{
			txt.htmlText = txt.htmlText + "\n\nopenHandler: " + event;
		}

		private function progressHandler(event:ProgressEvent):void
		{
			txt.htmlText = txt.htmlText + "\n\nprogressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal;
		}

		private function securityErrorHandler(event:SecurityErrorEvent):void
		{
			txt.htmlText = txt.htmlText + "\n\nsecurityErrorHandler: " + event;
		}

		private function httpStatusHandler(event:HTTPStatusEvent):void
		{
			txt.htmlText = txt.htmlText + "\n\nhttpStatusHandler: " + event;
		}

		private function ioErrorHandler(event:IOErrorEvent):void
		{
			txt.htmlText = txt.htmlText + "\n\nioErrorHandler: " + event;
		}
	}
}

Go out to the FLA file now and drop a TextArea component onto the stage and give it a name of “mytxt”. Then add some ActionScript to the first frame that looks like this:

var obj:URLLoaderExample = new URLLoaderExample(mytxt);

Normally this is not necessarily how you would go about instantiating the class but again, this is just a quick demo.

Now for the PHP file. Using the code below drop the file onto your PHP enabled server:

<?php

class Person
{
   public $first_name;
   public $last_name;
   public $email;
}

if(isset($_GET['getPerson']))
{
   $jsonString = urldecode(@file_get_contents('php://input'));
   $jsonString = str_replace("\\", "", $jsonString);
   $data = json_decode($jsonString, true);

   $p = new Person();
   $p->first_name = $data['first_name'];
   $p->last_name = $data['last_name'];
   $p->email = $data['email'];

   $pp = new Person();
   $pp -> first_name = "Jessica";
   $pp -> last_name = "Enders";
   $pp -> email = "jessica@gmail.com";

   $arr = array($p, $pp);

   echo json_encode($arr);
}

?>

Note: Make sure your Flash security settings allow you to connect to the web server your using.

Thats it. You ought to be able to run the Flash program and have it hit the PHP page and get some results back. Here are the results I get:

openHandler: [Event type="open" bubbles=false cancelable=false eventPhase=2]

progressHandler loaded:147 total: 0

httpStatusHandler: [HTTPStatusEvent type="httpStatus" bubbles=false cancelable=false eventPhase=2 status=200]

[{"first_name":"Frank","last_name":"Smith","email":"fsmith@nowhere.com"},{"first_name":"Jessica","last_name":"Enders","email":"jessica@gmail.com"}]

First Name: Frank

Last Name: Smith

Email: fsmith@nowhere.com
--------------------------------------

First Name: Frank

Last Name: Jones

Email: fjones@nowhere.com
--------------------------------------

If you hit the PHP page directly you will see this:

[{"first_name":null,"last_name":null,"email":null},{"first_name":"Jessica","last_name":"Enders","email":"jessica@gmail.com"}]

Obviously we are not doing anything with the data in the PHP file, we are simply returning what Flash sent us along with a new contact. However, all the basics are here to take this as far as you want.

Flash Source Code

11 Responses to “Getting Flash CS3 talking to PHP 5 via JSON”

  1. [...] Great set of coding examples of getting PHP5 and Flash CS3 (ActionScript 3) to work together. Tags: Actionscript, Flash, JSON, PHP [...]

  2. [...] – so don’t expect this to work the first time. Its certainly not as simple to setup IMHO as using PHP or Java, however once I got it working it was pretty slick and worked very [...]

  3. Andy says:

    Thanks a lot for posting this! It is really going to help me. Also, what are you using to dock your code in? Is that a WordPress plugin?

  4. Chad Lung says:

    @Andy

    I’m using the iG:Syntax Hiliter WordPress plugin for the code highlighting.

    Chad

  5. gabgren says:

    hi !
    i got this error when launching the flash:

    “1046: Type was not found or was not a compile-time constant: TextArea.”

    the type TextArea seems to be not recognized ’cause Flash is not able to load import fl.controls.TextArea (1172: Definition fl.controls:TextArea could not be found.)

    what’s the problem ?? (of course, i have Flash CS3 and an AS3 document)

  6. Chad Lung says:

    @gabgren
    Are you sure the import is coming after the package and before the class?
    package
    {
    import fl.controls.TextArea;

    public class URLLoaderExample
    {
    … etc

    Also, check to ensure that component is actually in your library.

    Chad

  7. kassel says:

    Please i need one explaination , why we must user str_replace under php, becose the conexion will be fluent, and no need other translations.
    Thsnks and sorry with my english

  8. Chad Lung says:

    @kassel,

    Depending how you actually implement this you may not need the str_replace at all.

  9. revathy says:

    As i am a beginner to flash field i need full php code to embed a flash file into a php give me a sample with description to execute it.

  10. Jason Wiener says:

    Great tutorial. Worked on the first try. Well done.

  11. Anonymous says:

    I get JSONParseError: Unexpected end of input

Leave a Reply