php解决跨域2022-07-18
2023-07-19 本文已影响0人
阿然学编程
/**
* 设置允许跨域请求
* @param array $allowedOrigins
*/
function handle_cors(array $allowedOrigins = array())
{
// 设置跨域请求头
$allowedHeaders = [
'Accept', 'Accept-Encoding', 'Accept-Language', 'Access-Token', 'Origin', 'Cookie',
'Content-Type', 'X-Requested-With', 'Authorization', 'Content-Length', 'Keep-Alive',
'Connection', 'User-Agent', 'X-CSRF-Token', 'Cache-Control', 'Pragma', 'X-Mx-ReqToken',
'Token'
];
// 判断当前请求的来源是否在白名单中
$http_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
$origin = in_array($http_origin, $allowedOrigins) ? $http_origin : '*';
// 设置其他允许的跨域请求头和方法
header('Access-Control-Allow-Origin: ' . $origin);
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: ' . implode(', ', $allowedHeaders));
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 7200'); // 预检请求的缓存时间,单位为秒
// 判断请求方法是否为 OPTIONS
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
exit();
}
}
- 使用示例
// 示例用法:在需要处理跨域的地方调用此函数
handle_cors();
// 在处理跨域请求之前调用 handleCors 函数
handle_cors(['http://example1.com', 'http://example2.com']);