Home > Backend Development > PHP Problem > How to solve cross-domain problems in php

How to solve cross-domain problems in php

王林
Release: 2023-03-08 06:20:01
forward
3416 people have browsed it

How to solve cross-domain problems in php

What is cross-domain?

Cross-domain means that the browser cannot execute scripts from other websites. It is caused by the browser's Same Origin Policy, a security restriction imposed by the browser.

The so-called same origin means that the domain name, protocol and port are the same.

1. Allow all domain names to access

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

2. Allow a single domain name to access

header('Access-Control-Allow-Origin: https://test.com');
Copy after login

3. Allow multiple domain names to access

In actual projects, the most It is best to specify a domain name that can be accessed across domains to increase security. It can be written in a public class to encapsulate a method call.

// 设置能访问的域名
static public $originarr = [
   'https://test1.com',
   'https://test2.com',
];
 
/**
 *  公共方法调用
 */
static public function setheader()
{
   // 获取当前跨域域名
   $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
   if (in_array($origin, self::$originarr)) {
      // 允许 $originarr 数组内的 域名跨域访问
      header('Access-Control-Allow-Origin:' . $origin);
      // 响应类型
      header('Access-Control-Allow-Methods:POST,GET');
      // 带 cookie 的跨域访问
      header('Access-Control-Allow-Credentials: true');
      // 响应头设置
      header('Access-Control-Allow-Headers:x-requested-with,Content-Type,X-CSRF-Token');
   }
}
Copy after login

Related recommendations: php tutorial

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

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template