
在做项目的过程中经常需要跨域访问。本篇文章主要就给大家介绍一下在php中怎么解决跨域问题。
1、允许所有域名访问
header('Access-Control-Allow-Origin: *');2、允许单个域名访问
header('Access-Control-Allow-Origin: https://test.com');相关推荐:《php教程》
3、允许多个域名访问
立即学习“PHP免费学习笔记(深入)”;
在实际项目中最好指定能跨域访问的域名,增加安全性。可以写在一个公共类里面,封装一个方法调用。
// 设置能访问的域名
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怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号