Proxy Scripting with PHP and Flash Tutorial - by: Flash-dB.com -© 2002 http://www.flash-db.com/Search/ProxyScriptingTutorial.php
Introduction
One of the greatest things about the internet is the wealth of free information and content available. Their are thousands of websites that allow you to use content from their websites and databases - and display it on yours. Some examples of this are stock quotes, Weather data, News stories, Search engine results, Auction listings, etc - the list goes on and on. Another important aspect of the internet are application service providers, some examples of these services could include CRM's (customer relationship management), Info sharing, sales tracking, e-business, Human resource's, desktop applications, etc - the list again goes on and on.
What do all of these have in Common? - All this data and all these services are not accessible directly by your Flash Movie. What if you wanted to include
constantly changing and updated weather reports from noaa - or stock quotes from Yahoo financial - or News feeds from Moreover - or send a new Lead to a CRM
service - or send payment information to Authorize.net for processing - or send and retrieve data from a database not located on your server. Well this
tutorial goes into one method which allows you to do all of this in Flash - with the User Never leaving your Site!
Recommended reading: "For security reasons, a Flash movie playing in a Web browser is not allowed to access data that resides outside the Web domain from which the SWF originated."
-http://www.macromedia.com/support/flash/ts/documents/loadvars_security.htm
Macromedia suggests two solutions or work arounds to this security feature, the first one is Proxy scripting the second involves DNS aliasing. This
article/tutorial will go over two examples of Proxy Scripting and how it can be used to create a more diverse and changing Flash movie/experience. I also put together an example of a search engine for a visual example of what this is all about. The search engine is based on Yahoo, but with the results of the search query sent from and displayed in Flash (included in the download) - For a
working version/example of the search engine visit -
http://www.flash-db.com/Search/. This is just one of many useful applications of this article. Their is also an example of using this method with moreover news at www.flash-db.com/News/.
This tutorial is not for everyone and it will not be possible for everyone to use this. 1) Since a server side script is needed, this script must be run on a server. 2) Some servers do not allow outgoing connections, if your server has this restriction then it will not be possible to run this script. (Some free and really large inexpensive commercial hosting companies will have this restriction due to their firewall settings). 3) These scripts are not needed
with Stand-Alone (exe) flash presentations - this is only needed for SWF files embedded in a Browser on the internet.
Overview
First it's necessary to define two types of Data/Content that we will be
accessing. 1) Static - this involves web pages that are not changing and are not based on information (query terms) that are passed to them. Examples of this would be Text files, HTML pages, and XML content - that reside on a server/domain outside of your own. 2) Dynamic - this involves web pages, database's, and other scripts that look up or perform queries based on the information you send to them.
Static: Loading static content/data from other servers is easier then loading dynamic content. This is because you will not have to build a request method such as "GET" or "POST". This is just fetching or grabbing static content from else where on the web and bringing it back to your flash movie. An example. If you wanted to you could also return Images, SWF's, mp3's, movies etc with this method - although since LoadMovie does not have this restriction their would be no sense in doing this with these types of files.
Dynamic: Dynamic content/data requires that a request be sent via "GET" or "POST". Then depending on the Data you send the page - it reacts and produces results based on your request Data. A good example of this is sending a Search engine a Search Term. If you wanted to search Google for "Flash" you would have to tell it to search for "Flash". Another example would be if you wanted to add a Sales Lead to a service that tracks this information for you. Or if you
wanted to send Credit card info to a credit card transaction processor. Or maybe add information to a database on a different server. Basically any time you have to send information to get information in return.
Tying it together: Basic Flow of data: From Flash -> to the Script -> To the external source -> Back to the script -> Back to Flash. The hardest part of all of this (because most data is not returned in nicely formatted XML) is parsing and formatting the data that is returned from the external source to a format Flash can easily display. Easy returned formats to work with include CSV (comma seperated values) TSV (Tab seperated values) - and of course XML (which does not require any parsing since Flash can already read XML). A lot of times you'll have to work with complex HTML stuff coming back which is the hardest to format and parse for use in Flash. This is the real art behind all of this.
Thoughts: Macromedia added this security restriction (external data is not accessible) because Flash can Loop and no user action is needed to send out a request via "GET" or "POST". So at first you might think "Big deal" - but if you look at this further and keep in mind past DOS (denial of service) attacks, you'll see that Macromedia was right by adding this security feature and did so with good reason. What if someone put up hundreds/thousands of really simple Flash movies all over on free web servers that sent out
second. This could become a problem and reduce the performance (or crash) the website that was being targeted. (This last paragraph is just an thought - and may or may not be plausible).
Part I: Building Static Requests
To include a text file, html file, XML file, etc from a different server/domain - only a simple script is needed. In the Flash movie you would have something like this:
loadVariablesNum("GetFile.php",0);
You would also have a dynamic text box named 'Results'. After calling the script this text area would be populated with the information at the URL your requesting. Here's the script:
<?php 1) $URL = "http://www.somesite.com/Data.txt"; 2) $fp = fopen( $URL,"r"); 3) $Results = fread($fp, 800000); 4) fclose( $fp ); 5) print "Results=$Results"; ?>
What this does:
Line 1: First we specify a URL to open.
Line 2: We open and assign the URL to a file pointer ($fp).
Line 3: Reads the data contained at that URL and gives it a variable name of $Results. In this case their is a limit of 800000 (which is big enough for almost anything).
Line 4: Closes the file pointer.
Line 5: Prints the results to the page. The format of 'Variable=Value' is needed so that flash can read in the data. At this point the data is sent back to Flash - and will appear in the text area named 'Results'.
You can use this same method with an XML file using the XMLSocket Object's methods and the XML Object's send and sendAndLoad The concept is the same -although the format and method that Flash calls the file would be different. To have this working with XML - I would recommend looking over one of the many XML tutorials out their and combining the idea's contained on those tutorials
with this Tutorial. In this fashion loading XML content from external servers/domains is possible - and relatively easy.
The URL can be any type of file including .html, .csv, .txt, .tsv, RSS, WDDX, etc. You can also load mp3's, images, other swf's, movies, etc from other servers with that above script (with MX)- however you would use LoadMovie instead of LoadVariables, and because LoadMovie does not have the same
restrictions as LoadVariables - it would not be necessary to use the script. Part II: Building Dynamic Requests
It is assumed that the readers of this article will be able to pass
information/variables from the Flash movie to the Script, the method of which they are passed does not matter (ie Get, Post, attach to end of query string) -as long -as they get their. This is accomplished with the LoadVariables
Actionscript function.
Once the script is called it begins the process as follows: Builds the request variables. Puts the variables into the correct format. Builds the request Method (either GET or POST). Opens a connection to the external source and sends the request. Awaits the return of Information from the request. Then formats the data and prints it out to the page - which is then returned to the Flash movie. This is building a Form without a Form.
The below script is the basis for the above process. The script was written in PHP - the procedure should be the same for all scripting languages however. As an example we will open up a connection to Yahoo - but keep in mind that this can be any URL. Also note that the 3 variables we are sending to it - can be any variables. The Line by Line comments below the script will better help you understand what this is doing.
1) <?php
2) $FormURL = "http://search.yahoo.com/search";
3) $FormMethod = "GET"; // You can specify either GET or POST on this line. 4) $FormData['p'] = $SearchTerm; //SearchTerm would be a variable sent from the Flash movie.
5) $FormData['o'] = '1';
6) $FormData['n'] = $numResult; //numResults would also be a variable sent from the Flash movie
//numResults would be assigned to the a variable called n -for example.
7) $QueryString = "";
8) foreach ($FormData as $name => $value) { 9) if (strlen($QueryString) > 0)
10) $QueryString .= '&';
11) $QueryString .= $name.'='.urlencode($value); 12) }
13) $url = parse_url($FormURL); 14) $request = $FormMethod." "; 15) switch ($FormMethod) { 16) case 'GET': 17) $request .= $url['path']."?".$QueryString." HTTP/1.1\r\n". 18) "Host: ".$url['host']."\r\n\r\n"; 19) break; 20) case 'POST': 21) $request .= $url['path']." HTTP/1.1\r\n". 22) "Host: ".$url['host']."\r\n". 23) "Content-type: application/x-www-form-urlencoded\r\n". 24) "Content-length: ".strlen($QueryString)."\r\n\r\n". 25) $QueryString; 26) break; 27) default:
28) die("Must specify a form method"); 29) }
30) $fp = fsockopen($url['host'], 80, $err_num, $err_msg, 30); // Submit form data
31) fputs($fp, $request); // Get the response
32) while (!feof($fp))
33) $response .= fgets($fp, 1024); 34) fclose($fp);
35) Print "Results=$response"; Line 1: Starts off the script.
Line 2: Indicates which URL to request.
Line 3: Tells the script what request method to use - either "GET" or "POST". Lines 4-6: These are variable/value combinations that you will be sending. You can either specify these in the script or send them from the Flash movie. As an example for this case - the variable 'SearchTerm' is sent from the Flash movie and assigned to a variable called 'o' which Yahoo bases the query on. These however can be any variable/value combo. Their is no real limit on how many of these you can have. Their will be a limit on the amount of data they contain if your sending a request via "GET" but in almost all case's you'll never reach that limit.
Lines 8-12: Builds the Query String that you will be sending.
Line 13: Parse's the URL and returns it's individual parts or components. Line 14: Starts to build the request.
Lines 15-29: This is a switch statement (much like and If/then statement). If the request method is "GET" it will build a request using the "GET" method. If the request is "POST" it will build the request using the "POST" method. This is determined by what you specify in Line 3. Building the request method in this way simulates (exactly) what it would look like if you where to use a Form to submit this same data. This form however does not require any user
interaction - and can technically be run at any time.
Line 30: The fsockopen function opens a socket connection to the URL we
specified in line 2 of the script. It then assigns this info to a file pointer ($fp). This is then used in the next couple of lines.
Line 31: The next line uses the fputs function, this submits the request that we built in lines 15-29 to the connection we opened in line 30.
Lines 32-34: After we submit the request - the page will send back the results. These lines read in those results Line by Line and assign them to the variable $response.
Line 35: This will print out all of the data contained in the $response variable to the page. In this case - The results of this script would look
exactly like what the web page who's URL we entered in on line 2 - Except on our server. As I mentioned earlier most of the time this data will come back as HTML (since most websites do not go out of their way to create a format that can
easily be read by flash) - The hard part is formatting and parsing that data so that Flash can display it.
If you had a Dynamic text area called 'Results' in your flash movie - and you used LoadVariables to call this script - then the dynamic Text area called 'Results' would contain all the text data contained in the $response.
Wow that was sort of confusing. If you start playing around with the script and sending query's to different URL's it will become easier to see how to retrieve the Info back to the Flash movie. If you have any questions on this script you can ask them Here.
Conclusion
In conclusion the idea's and scripts contained in this article will make it possible for you to include data from any source in your Flash movie. As stated over and over again - the hardest part of all of this is parsing and formatting the returned data in a way that Flash can easily display it. Since most services
return information formatted as somewhat complex html - this can become difficult and time consuming.
Hopefully by reading over this tutorial you get an idea of what is possible when Flash uses a proxy script such as the ones presented. Because Flash has many advantages over HTML (such as: not needing to be refreshed or requiring a user action to load new content/data) and allowing much greater flexibility. The use of the scripts and idea's presented should make it possible for many new
applications and ways to use Flash. -Jeffrey F. Hill
Questions: Flash-db Board http://www.flash-db.com