PHP cross-domain problem solution

angryTom
Release: 2023-04-07 15:36:01
forward
6788 people have browsed it

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

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

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

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!

Related labels:
source:www.whmblog.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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!