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‘); ??}}
PHP跨域访问
原文地址:https://www.cnblogs.com/sgm4231/p/10043811.html