Simple Ajax Uploader - CORS

Simple Ajax Uploader includes built-in support for cross-domain file uploading (as of version 1.9). All modern browsers are supported, along with IE8 and IE9.

How to Enable CORS

  1. Set the cors option to true in your Javascript configuration.
  2. Include cors.php at the top of your server-side script (handles HTTP response headers).
  3. (optional) To support IE8 and IE9, wrap all server responses in the corsResponse() method of the FileUpload PHP class. For example:

    $upload = new FileUpload('uploadfile');
    $response json_encode( array( 'success' => true ) );
    $upload->corsResponse$response ); // Response wrapped in corsResponse()

How it Works

Security restrictions in IE8 and IE9 prevent directly accessing the contents of an iframe that originated from a different domain. One workaround is to use window.postMessage, which allows messages to be sent between windows/frames from different domains.

When CORS is enabled in browsers without XHR upload support, an additional parameter named XHR_CORS_TARGETORIGIN is added, which contains the value of window.location.href. This serves to notify the server that the response must be made through window.postMessage.

On the server, when corsResponse() detects that XHR_CORS_TARGETORIGIN is set, the response is wrapped in a Javascript snippet which triggers the message event, which in turn delivers the response through the iframe.

Here is what corsResponse() looks like:


function corsResponse$data ) {
  if ( isset( 
$targetOrigin $this->escapeJS$_REQUEST['XHR_CORS_TARGETORIGIN'] );
$targetOrigin htmlspecialchars$targetOriginENT_QUOTES'UTF-8' );

As you can see, when XHR_CORS_TARGETORIGIN is not set, the response is returned as-is — modern browsers do not need this workaround.

More Info

MDN - HTTP access control (CORS)

HTML5 Rocks - Using CORS

MDN - Window.postMessage

David Walsh - HTML5 window.postMessage API

John Resig - Cross-Window Messaging