The Flash Player doesn’t allow you to load and use data from other domains, even a subdomain of where you SWF is being served from. Normally this can be worked around by editing the policy file, crossdomain.xml, of the domain where the data is located, but what can you do when the data you want to load is owned by someone like Facebook or Twitter? Chances are that you don’t have the kind of pull it would take to get them to change their policy files, so it’s time to implement a web service on the domain where the SWF is hosted.
I ran into this problem while working with the Twitter and Facebook APIs on my site. Their APIs allow you to get names, URLs, and other interesting data points, but I wanted to load images, which aren’t delivered through the API. To solve this problem, I wrote this dead-simple PHP script which simply forwards GET requests to a URL specified in the “url” parameter and displays the result back to the requester:
<?php $content = file_get_contents($_GET['url']); if ($content !== false) { echo($content); } else { // there was an error } ?>
Of course this is the most simple of examples of a web service that you can get, and is really only useful for simple content like XML, HTML and images. Anything more complicated than this and you would want to create a proper web service with input validation, caching, etc., but this is a quick way to get up and running.
Note that your browser won’t render the proxy-ed image correctly because it doesn’t receive the correct content-type header, which tells the browser to expect an image. What you’re seeing is actually the ASCII representation of the image’s binary data, known as BitmapData to the AS3 world.
Bonus! It can be slow to go through your proxy when not needed, so I use this simple class to create URLRequests with the proper URL as determined by the SWF’s security sandbox:
package com.bdement.proxy { import flash.net.URLRequest; import flash.system.Security; public class ProxyService { public static const PROXY_URL:String = "http://www.brandondement.com/proxy.php?url="; public function ProxyService() { throw new Error("All methods of ProxyService are static, do not instantiate!"); } public static function getProxyRequest(url:String) : URLRequest { if(url == null) return new URLRequest(); return new URLRequest((isLocal ? "" : PROXY_URL) + url); } public static function toProxySource(source:String) : String { if(source == null) return null; return (isLocal ? "" : PROXY_URL) + source; } public static function get isLocal() : Boolean { return ( Security.sandboxType == Security.LOCAL_TRUSTED || Security.sandboxType == Security.LOCAL_WITH_NETWORK); } } }