PHP implements server-side to allow client-side ajax cross-domain

little bottle
Release: 2023-04-06 07:44:02
forward
3001 people have browsed it

This article mainly talks about using PHP to implement server-side allowing client-side ajax cross-domain. Friends in need can refer to it.

The key to solving cross-domain issues 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, there will be the following error: This article mainly talks about

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 single domain name access
If you specify a domain name http://api.itbsl.com for cross-domain access, you only need to access it at http:// Add the following code to the header of the www.itbsl.com/server.php file:

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

2. Allow multiple domain names to access
Specify multiple domain names http://api.itbsl.com, http:/ /doc.itbsl.com and other cross-domain access, you only need to add the following code in 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);       
}
Copy after login

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

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

Related videos: ajax video tutorial

The above is the detailed content of PHP implements server-side to allow client-side ajax cross-domain. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:cnblogs.com
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template