Home  >  Article  >  Backend Development  >  PHP cross-domain problem solution

PHP cross-domain problem solution

angryTom
angryTomforward
2019-10-14 17:19:206752browse

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(&#39;Access-Control-Allow-Origin:http://client.php.cn&#39;);

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[&#39;HTTP_ORIGIN&#39;])? $_SERVER[&#39;HTTP_ORIGIN&#39;] : &#39;&#39;;  
$allow_origin = array(  
    &#39;http://client1.php.cn&#39;,  
    &#39;http://client2.php.cn&#39;  
);

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(&#39;Access-Control-Allow-Origin:*&#39;);

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!

Statement:
This article is reproduced at:www.whmblog.cn. If there is any infringement, please contact admin@php.cn delete