The Best Solution to the PHP Ajax Cross-Domain Issue
Category Programming Technology
This article implements cross-domain access by setting Access-Control-Allow-Origin.
For example: The client's domain name is client.tutorialpro.org, and the requested domain is server.tutorialpro.org.
If you access it directly with ajax, you will encounter the following error:
XMLHttpRequest cannot load http://server.tutorialpro.org/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://client.tutorialpro.org' is therefore not allowed access.
1. Allow access from a single domain
To allow cross-domain access from a specific domain (http://client.tutorialpro.org), simply add the following code to the top of the http://server.tutorialpro.org/server.php file:
header('Access-Control-Allow-Origin:http://client.tutorialpro.org');
2. Allow access from multiple domains
To allow cross-domain access from multiple domains (http://client1.tutorialpro.org, http://client2.tutorialpro.org, etc.), simply add the following code to the top of the http://server.tutorialpro.org/server.php file:
$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
$allow_origin = array(
'http://client1.tutorialpro.org',
'http://client2.tutorialpro.org'
);
if(in_array($origin, $allow_origin)){
header('Access-Control-Allow-Origin:'.$origin);
}
3. Allow access from all domains
To allow access from all domains, simply add the following code to the top of the http://server.tutorialpro.org/server.php file:
header('Access-Control-Allow-Origin:*');
** Click to Share Notes
-
-
-