This article achieves cross-domain by setting Access-Control-Allow-Origin. For example: the client's domain name is client.php.cn, and the requested domain name is server.php.cn. If you use ajax to access it directly, you will get the following error:
XMLHttpRequest cannot load http:/server.php.cn/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://client.php.cn' is therefore not allowed access.
1. Allow single domain name access
specified For cross-domain access to a certain domain name (http://client.php.cn), you only need to add the following code to the header of the http://server.php.cn/server.php file:
<?php header('Access-Control-Allow-Origin:http://client.php.cn');
2. Allow multiple domain names to access
If you specify multiple domain names (http://client1.php.cn, http://client2.php.cn, etc.) for cross-domain access, you only need to Add the following code to the header of the http://server.php.cn/server.php file:
<?php $origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : ''; $allow_origin = array( 'http://client1.php.cn', 'http://client2.php.cn' );
3. Allow all domain names to access
Allow all domain names to access Then just add the following code to the header of the http://server.php.cn/server.php file:
<?php header('Access-Control-Allow-Origin:*');
For more PHP related knowledge, please visit PHP Chinese website!
The above is the detailed content of PHP cross-domain problem solution. For more information, please follow other related articles on the PHP Chinese website!