* @param string $url 请求的URL
* @param string $method 请求方法,默认是'GET'
* @param string $back 返回类型,默认为空,可以为'all'或'cookie'
* @param array $params 请求参数,默认为空数组
* @param array $headers 请求头,默认为空数组
* @return array 响应数据
function sendCurlRequest($url, $method = 'GET', $back = "", $params = [], $headers = []) {
// 初始化cURL会话
$ch = curl_init();
// 设置请求URL
if ($method == 'GET' && !empty($params)) {
$url .= '?' . http_build_query($params);
curl_setopt($ch, CURLOPT_URL, $url);
// 设置请求方法
if($method == 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
// 返回而不是输出内容
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 允许跟随重定向
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// 设置返回类型
if ($back === "all") {
// 设置为true以包含响应头
curl_setopt($ch, CURLOPT_HEADER, true);
// 设置为false以包含响应体
curl_setopt($ch, CURLOPT_NOBODY, false);
} elseif ($back === "cookie") {
// 设置为true以包含响应头
curl_setopt($ch, CURLOPT_HEADER, true);
// 设置请求头
if (!empty($headers)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// 设置超时(可选)
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
// 执行cURL会话
$response = curl_exec($ch);
// 获取HTTP状态码
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 获取错误信息
$error = curl_error($ch);
// 处理cookie
$cookies = [];
if ($back == "cookie" || $back == "all") {
// 分离头部和主体
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
if ($back == "all") {
$body = substr($response, $header_size);
// 解析头部中的Cookie
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $header, $matches);
foreach ($matches[1] as $item) {
parse_str($item, $cookie);
$cookies = array_merge($cookies, $cookie);
// 关闭cURL会话
curl_close($ch);
// 构建返回数据
if ($error) {
$data = ['code' => 400, 'msg' => $error];
} else if ($httpCode >= 400) {
$data = ['code' => 400, 'msg' => "HTTP error $httpCode"];
} else if ($back == "all") {
$data = ['code' => 200, 'cookie' => $cookies, 'body' => $body];
} else if ($back == "cookie") {
$data = ['code' => 200, 'cookie' => $cookies];
} else {
$data = ['code' => 200, 'body' => $response];
// 返回响应数据
return $data;