当前位置: 移动技术网 > IT编程>开发语言>PHP > PHP解决跨域问题

PHP解决跨域问题

2018年11月10日  | 移动技术网IT编程  | 我要评论

在做项目的过程中经常需要跨域访问。这里主要介绍一下 php 中怎么解决跨域问题。

1、允许所有域名访问

header('access-control-allow-origin: *');

2、允许单个域名访问

header('access-control-allow-origin: https://test.com');

3、允许多个域名访问

  • 在实际项目中最好指定能跨域访问的域名,增加安全性。可以写在一个公共类里面,封装一个方法调用。
// 设置能访问的域名
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');
   }
}

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网