How to implement cross-domain requests in php

王林
Release: 2023-03-12 21:16:02
Original
6628 people have browsed it

How to implement cross-domain requests in php: You can allow access to all domain names by setting [header('Access-Control-Allow-Origin:*');].

How to implement cross-domain requests in php

The operating environment of this article: windows10 system, php 7, thinkpad t480 computer.

In PHP, if we need to implement cross-domain, we can do it by setting Access-Control-Allow-Origin. Next, let’s give an example to help everyone understand better.

Assume that the current client domain name is client.runoob.com, and the requested domain name is server.runoob.com.

If we use ajax to access directly, the following error will occur:

XMLHttpRequest cannot load http://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.
Copy after login

1. Allow a single domain name to access

Specify a domain name (http://client.runoob. com) for cross-domain access, you only need to add the following code to the header of the http://server.runoob.com/server.php file:

header('Access-Control-Allow-Origin:http://client.runoob.com');
Copy after login

2. Allow multiple domain names to access

To specify multiple domain names (http://client1.runoob.com, http://client2.runoob.com, etc.) for cross-domain access, you only need to add the file header at http://server.runoob.com/server.php Add the following code:

$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';  
  $allow_origin = array(  
    'http://client1.runoob.com',  
    'http://client2.runoob.com'  );  
  if(in_array($origin, $allow_origin)){  
    header('Access-Control-Allow-Origin:'.$origin);       }
Copy after login

3. Allow all domain names to access

To allow all domain names to access, just add the file header at http://server.runoob.com/server.php Add the following code:

header('Access-Control-Allow-Origin:*');
Copy after login

Recommended learning: php training

The above is the detailed content of How to implement cross-domain requests in php. For more information, please follow other related articles on the PHP Chinese website!

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