设为首页 加入收藏

TOP

PHP解决跨域问题
2019-08-23 00:37:33 】 浏览:23
Tags:PHP 解决 问题

在做项目的过程中经常需要跨域访问。这里主要介绍一下 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');
   }
}

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇数据库备份的两种方法 下一篇Windows系统XAMPP安装Moodle教程

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目