The best solution to PHP Ajax cross-domain problems

WBOY
Release: 2016-07-28 08:29:38
Original
880 people have browsed it

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>
Copy after login
<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>
Copy after login

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>
Copy after login

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>
Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template