Home  >  Article  >  Backend Development  >  How does PHP solve cross-domain access problems? (code example)

How does PHP solve cross-domain access problems? (code example)

青灯夜游
青灯夜游forward
2018-11-22 15:33:005290browse

The content of this article is to introduce how PHP solves cross-domain access problems? (Code sample), let everyone know how to achieve cross-domain access. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In the process of working on projects, cross-domain access is often required. This article mainly introduces to you how to solve cross-domain problems in PHP.

1. Allow access to all domain names

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

2. Allow access to a single domain name

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

3. Allow multiple domain names to access

In actual projects, it is best to specify domain names 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');
   }
}

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study. Recommended more related video tutorials: PHP tutorial!

The above is the detailed content of How does PHP solve cross-domain access problems? (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete