PHP Proxy for Flash

September 19th, 2008

Need to avoid the damn Flash cross-domain security restrictions?

I ran into numerous problems on a recent Flash build. Mainly as I was compiling via the FlexSDK on the command line and testing in an open browser. Not ideal, and I really hit some problems when cross-domain restrictions came to play.

Lucky for me Mr Apache and his best friend PHP came out to play, and I wrote a snippy little proxy class to request the files through. Bypassing the need for a cross-domain as all the files we’re being hosted on the localhost. Beauuutiful.

So in true Open Source style, here’s the proxy class in all it’s glory. A couple of things:

  • Ensure you’re running PHP5
  • You’ll need to view your SWF through the localhost. So on a Mac, that’s view the files via your site folder

The source code is below, otherwise download this ZIP: Proxy.php


requestURL = $queryVars[ self::$QUERY_URL ];
			$this->headers = isset($queryVars[ self::$QUERY_HEADER ]);

			if(isset($queryVars[ self::$QUERY_MIMETYPE ]))
			{
				$this->mimeType = $queryVars[ self::$QUERY_MIMETYPE ];
			}

			if( $this->startCurlSession() )
			{
				if ($requestType == self::$REQUEST_TYPE_POST) {
					$this->makePostRequest();
				}

				if($repsonse = $this->makeRequest())
				{
					if ($this->mimeType)
					{
						header(”Content-Type: ” . $this->mimeType);
					}
					echo($repsonse);
				}

				$this->stopCurlSession();
			}
		}
	}
	/**
	 * Initiates CURL session into current object
	 *
	 * @param	void
	 * @return	void
	 */
	private function startCurlSession ()
	{
		if($this->curlSession = curl_init($this->requestURL))
		{
			return(true);
		}
		return(false);
	}
	/**
	 * Closes current CURL session
	 *
	 * @param	void
	 * @return	void
	 */
	private function stopCurlSession ()
	{
		if(curl_close($this->curlSession))
		{
			return(true);
		}
		return(false);
	}
	/**
	 * Generates and commits CURL command to external server
	 *
	 * @param	void
	 * @return	string
	 */
	private function makeRequest ()
	{
		curl_setopt($this->curlSession, CURLOPT_HEADER, ($this->headers) ? true : false);
		curl_setopt($this->curlSession, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($this->curlSession, CURLOPT_RETURNTRANSFER, true);

		return(curl_exec($this->curlSession));
	}
	/**
	 * Creates POST headers (if needed)
	 *
	 * @param	void
	 * @return	void
	 */
	private function makePostRequest ()
	{
		$post_vars = Array();
		$ignore = Array( self::$QUERY_URL, self::$QUERY_MIMETYPE, self::$QUERY_HEADER);
		foreach($_POST as $key => $value) {
			if(!in_array($key, $ignore))
			{
				$post_vars[] = $key . ‘=’ . $value;
			}
		}
		curl_setopt ($this->curlSession, CURLOPT_POST, true);
		curl_setopt ($this->curlSession, CURLOPT_POSTFIELDS, implode(”&”, $post_vars));
	}
}

// Instantiate
$cdpr = new CrossDomainProxyRequest( CrossDomainProxyRequest::$REQUEST_TYPE_GET );
?>

Subscribe to this blog