Home >Backend Development >PHP Problem >Server-side php settings allow cross-domain methods

Server-side php settings allow cross-domain methods

L
LOriginal
2020-05-30 16:59:465417browse

Server-side php settings allow cross-domain methods

Server-side php settings allow cross-domain

The key to solving cross-domain is to set Access-Control-Allow-Origin.
For example: the client's domain name is api.itbsl.com, and the requested domain name is www.itbsl.com
If you use ajax to access it directly, the following error will occur:

XMLHttpRequest cannot load http://www.itbsl.com/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://api.itbsl.com' is therefore not allowed access .

1. Allow a single domain name to access
If you specify a domain name http://api.itbsl.com for cross-domain access, you only need to access it at http://www.itbsl.com/server Add the following code to the header of the .php file:

header('Access-Control-Allow-Origin:http://api.itbsl.com');

2. Allow multiple domain names to access
Specify multiple domain names http://api.itbsl.com, http://doc.itbsl.com, etc. For cross-domain access, you only need to add the following code to the header of the http://www.itbsl.com/server.php file:

$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';   
$allow_origin = array(      'http://api.itbsl.com',      'http://doc.itbsl.com'  );    
if(in_array($origin, $allow_origin)){  
    header('Access-Control-Allow-Origin:'.$origin);    
}

3. Allow all domain names to access
Allow all domain names To access, just add the following code to the header of the http://www.itbsl.com/server.php file:

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

Recommended tutorial: "PHP Tutorial"

The above is the detailed content of Server-side php settings allow cross-domain methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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