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