Home>Article>Backend Development> PHP implements server-side to allow client-side ajax cross-domain
This article mainly talks about using PHP to implement server-side allowing client-side ajax cross-domain. Friends in need can refer to it.
The key to solving cross-domain issues is to setAccess-Control-Allow-Origin.
For example: the client's domain name is api.itbsl.com, and the requested domain name is www.itbsl.com
If you use ajax to access it directly, there will be the following error: This article mainly talks about
XMLHttpRequest cannot load http://www.itbsl.com/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://api.itbsl. com' is therefore not allowed access.
1. Allow single domain name access
If you specify a domain name http://api.itbsl.com for cross-domain access, you only need to access it at http:// Add the following code to the header of the www.itbsl.com/server.php file:
header('Access-Control-Allow-Origin:http://api.itbsl.com');
2. Allow multiple domain names to access
Specify multiple domain names http://api.itbsl.com, http:/ /doc.itbsl.com and other cross-domain access, you only need to add the following code in the header of the http://www.itbsl.com/server.php file:
$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : ''; $allow_origin = array( 'http://api.itbsl.com', 'http://doc.itbsl.com' ); if(in_array($origin, $allow_origin)){ header('Access-Control-Allow-Origin:'.$origin); }
3. Allow all domain names to access
To allow access from all domain names, just add the following code to the header of the http://www.itbsl.com/server.php file:
header('Access-Control-Allow-Origin:*');
Related videos:ajax video tutorial
The above is the detailed content of PHP implements server-side to allow client-side ajax cross-domain. For more information, please follow other related articles on the PHP Chinese website!