A lot of the Flash and Flex applications I build are dynamically driven by XML. As many ActionScript devs know, a crossdomain.xml file is required to pull XML from a server that’s separate from the one where the SWF resides.
Until now, I’ve always used local XML documents, had access to the server where the XML was being served and could put a crossdomain.xml file in place, or had access to a public API that provided an XML feed and had a crossdomain.xml file already in place. But an application I’m working on now uses XML from a server where I have no access or ability to put a crossdomain.xml file.
Enter the PHP proxy and the ActionScript escape method. A PHP script handles the URL for the API call, but you have to encode that URL with its arguments before handing off to the proxy.
Example:
Here’s the code for the PHP proxy file, which goes on the same server as your SWF.
$post_data = $HTTP_RAW_POST_DATA;
$header[] = "Content-type: text/xml";
$header[] = "Content-length: ".strlen($post_data);
$ch = curl_init( $_GET['url'] );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
if ( strlen($post_data)>0 ){
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
}
$response = curl_exec($ch);
$response_headers = curl_getinfo($ch);
if (curl_errno($ch)) {
print curl_error($ch);
} else {
curl_close($ch);
header( 'Content-type: ' . $response_headers['content-type']);
print $response;
}
(Thanks to xmlrpcflash.mattism.com for the PHP script.)
Now, assuming you are using a Loader with a URLRequest to pull XML into your application, and your xml_proxy.php file is in the same directory as your SWF, you have to escape( ) on the URL call to the API server, then tack that on to the end of your URLRequest to the PHP proxy, like this:
var myXMLLoader:URLLoader = new URLLoader();
var API_URL:String = escape("http://theAPIServer.com?app_id=d57&app_key=e9409&format=xml");
myXMLLoader.load(new URLRequest("xml_proxy.php?url="+API_URL));
Voila! No security sandbox error from Flash Player.