<?php
// 允许跨域访问
header("Access-Control-Allow-Origin: http://localhost:19006");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
// 设置允许携带凭据(credentials)跨域访问
header("Access-Control-Allow-Credentials: true");
// 获取请求方法
$method = $_SERVER['REQUEST_METHOD'];
// 获取前端请求的 Content-Type
$requestContentType = isset($_SERVER["HTTP_CONTENT_TYPE"]) ? $_SERVER["HTTP_CONTENT_TYPE"] : '';
// 获取目标URL,替换域名
$url = 'http://test.com' . $_SERVER['REQUEST_URI'];
$url = str_replace($_SERVER['SCRIPT_NAME'], '', $url);
// 获取所有的请求头
$requestHeaders = array();
foreach ($_SERVER as $key => $value) {
if (substr($key, 0, 5) === 'HTTP_') {
$headerKey = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($key, 5)))));
if($headerKey == 'Content-Type'){
$requestHeaders[] = $headerKey . ': ' . $value;
}
if($headerKey == 'Accept-Language'){
$requestHeaders[] = $headerKey . ': ' . $value;
}
}
}
// 初始化cURL会话
$ch = curl_init($url);
// 根据请求方法设置cURL选项
if ($method === 'POST') {
// 获取请求体数据
$data = file_get_contents('php://input');
if (!empty($data)) {
curl_setopt($ch, CURLOPT_POST, 1);
// 根据前端请求的Content-Type设置适当的请求头
// curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: ' . $requestContentType));
// curl_setopt($ch, CURLOPT_HTTPHEADER, [$requestHeaders[2],$requestHeaders[3]]);
curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
// 设置请求体
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
} else {
// 请求体为空,返回错误或适当的响应
http_response_code(400); // Bad Request
exit('Empty request body');
}
}
// 设置其他cURL选项
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true); // 返回头部信息
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
// 执行cURL请求
$response = curl_exec($ch);
// 检查cURL是否出错
if (curl_errno($ch)) {
// 处理cURL错误,返回适当的响应
http_response_code(500); // Internal Server Error
echo 'cURL error: ' . curl_error($ch);
exit;
}
// 关闭cURL会话
curl_close($ch);
// 分离响应头和响应体
list($header, $body) = explode("\r\n\r\n", $response, 2);
// 提取并设置Cookie
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $header, $matches);
$cookies = array();
foreach ($matches[1] as $item) {
parse_str($item, $cookie);
$cookies = array_merge($cookies, $cookie);
}
// 设置Cookie
foreach ($cookies as $name => $value) {
setcookie($name, $value, time() + 86400, '/', 'localhost'); // 这里可以根据需要调整cookie的过期时间和路径
}
// 输出响应
echo $body;
网友评论