This article achieves cross-domain by setting Access-Control-Allow-Origin.
For example: the client’s domain name is client.runoob.com, and the requested domain name is server.runoob.com.
If you use ajax to access directly, there will be the following error:
<span>XMLHttpRequest</span><span> cannot load http</span><span>:</span><span>//server.runoob.com/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://client.runoob.com' is therefore not allowed access.</span>
<p>1、允许单个域名访问</p><p>指定某域名(http://client.runoob.com)跨域访问,则只需在http://server.runoob.com/server.php文件头部添加如下代码:</p><pre class="brush:php;toolbar:false"><span>header</span><span>(</span><span>'Access-Control-Allow-Origin:http://client.runoob.com'</span><span>);</span>
2. Allow multiple domain names to access
Specify multiple domain names (http://client1.runoob.com, http://client2.runoob.com, etc. ) for cross-domain access, you only need to add the following code to the header of the http://server.runoob.com/server.php file:
<span>$origin </span><span>=</span><span> isset</span><span>(</span><span>$_SERVER</span><span>[</span><span>'HTTP_ORIGIN'</span><span>])?</span><span> $_SERVER</span><span>[</span><span>'HTTP_ORIGIN'</span><span>]</span><span>:</span><span>''</span><span>;</span><span>$allow_origin </span><span>=</span><span> array</span><span>(</span><span>'http://client1.runoob.com'</span><span>,</span><span>'http://client2.runoob.com'</span><span>);</span><span>if</span><span>(</span><span>in_array</span><span>(</span><span>$origin</span><span>,</span><span> $allow_origin</span><span>)){</span><span> header</span><span>(</span><span>'Access-Control-Allow-Origin:'</span><span>.</span><span>$origin</span><span>);</span><span>}</span>
3. To allow access from all domain names
To allow access from all domain names, you only need to add the following code at http: //Server.runoob.com/server.php file header add the following code:
<span>header</span><span>(</span><span>'Access-Control-Allow-Origin:*'</span><span>);</span>
The above introduces the best solution to the PHP Ajax cross-domain problem, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.