php 子域名进行跨域操作

本地配置两个域名:

http://www.concent.com   主域名

http://s.concent.com/       子域名

在主域名下添加跨域代码:

ini_set('session.cookie_domain','.concent.com'); // 设置子域名也有效
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
header("Access-Control-Allow-Headers: VERSION,token,If-Modified-Since,currentcity,currentprovince, Content-Type");
header("Access-Control-Allow-Methods: HEAD,GET,POST,DELETE,PUT,OPTIONS");

$allow_origin = array(
    'http://localhost:8088',
    'http://s.concent.com',   // 允许跨域 的名单
);
if (in_array($origin, $allow_origin)) {
    header('Access-Control-Allow-Origin:' . $origin);
    header('Access-Control-Allow-Credentials:true');
}
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit;
}

子域名下 ajax 请求:

<script src='https://code.jquery.com/jquery-3.0.0.min.js'></script>
<button onclick='tests()'>当前在子域名下测试获取session</button>
<script>
  function tests() { $.ajax({ type: 'get', url: 'http://www.concent.com/apiact/basics', data: '', xhrFields: {withCredentials: true}, // 携带 cookie 参数 //crossDomain: true, success: function(msg){ console.log(msg); } });
  }
</script>

会发现携带了cookie参数(和主域名返回的保持一致):

测试 在主域名登录,然后 切换到子域名下也显示登录成功了:

猜你喜欢

转载自www.cnblogs.com/xdtx/p/9633115.html
今日推荐