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.
cors
option to true
in your Javascript configuration.corsResponse()
method of the FileUpload
PHP class. For example:
<?php
require('cors.php');
require('Uploader.php');
$upload = new FileUpload('uploadfile');
...
$response = json_encode( array( 'success' => true ) );
echo $upload->corsResponse( $response ); // Response wrapped in corsResponse()
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:
<?php
function corsResponse( $data ) {
if ( isset( $_REQUEST['XHR_CORS_TARGETORIGIN'] ) ) {
$targetOrigin = $this->escapeJS( $_REQUEST['XHR_CORS_TARGETORIGIN'] );
$targetOrigin = htmlspecialchars( $targetOrigin, ENT_QUOTES, 'UTF-8' );
return "<script>window.parent.postMessage('$data','$targetOrigin');</script>";
}
return $data;
}
As you can see, when XHR_CORS_TARGETORIGIN
is not set, the response is returned as-is — modern browsers do not need this workaround.
MDN - HTTP access control (CORS)
Simple Ajax Uploader
More code projects from LPology