PHP-GET/POST整合一体封装函数直接调用

22 阅读1分钟

`<?php /* 本教程由接口盒子编辑 PHP通用GET/POST请求教程 */ //-----------------配置参数----------------- $config = array( 'url' => 'cn.apihz.cn/api/time/ge…', //请求地址,替换为实际地址 'type' => 1, // 请求方式 0=GET,1=POST //如果有参数内容较大,必须使用POST。 'data' => array( //请求参数 'id' => '88888888',//开发者ID 'key' => '88888888',//开发者KEY 'type' => 20, // 其他参数按格式增加 ),

// curl配置参数
'curl_options' => array(
    // 超时设置
    'connect_timeout' => 10,  // 连接超时时间(秒)
    'timeout' => 30,         // 整体超时时间(秒)
    
    // SSL设置
    'ssl_verify_peer' => false,  // 是否验证对等证书
    'ssl_verify_host' => false,  // 是否验证主机名
    
    // 其他设置
    'follow_location' => true,   // 是否跟随重定向
    'return_transfer' => true,   // 是否返回结果而不直接输出
    'encoding' => '',            // 响应的编码格式,如gzip
    
    // 代理设置
    'proxy' => '',               // 代理服务器地址,如'http://127.0.0.1:8080'
    'proxy_type' => CURLPROXY_HTTP,  // 代理类型
    'proxy_auth' => array(      // 代理认证
        'username' => '',
        'password' => ''
    ),
),

// 请求头
'headers' => array(
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.5845.97 Safari/537.36',
    'null' => null,//其他请求头按格式增加
),

// Cookie
'cookie' => '',

// 其他
'user_agent' => '',  // 单独设置User-Agent,优先级高于headers中的

);

//-----------------执行请求----------------- res=getpost(res = getpost(config);//返回内容 datas=jsondecode(datas = json_decode(res, true);//对返回内容进行JSON解析 if (json_last_error() === JSON_ERROR_NONE) { if(datas['code'] == 200){ echo datas['msg'];//返回状态码请求成功,取出对应的数据,执行自己的业务逻辑。 }else{ echo $datas['msg'];//返回状态码请求失败,取出对应的数据,执行自己的业务逻辑。 } }else{ echo json_encode(array( 'code' => 400, 'msg' => '解析JSON返回数据失败!' ), JSON_UNESCAPED_UNICODE); }

//-----------------封装函数----------------- function getpost(config) { // 验证必要参数 if (empty(config['url'])) { return json_encode(array( 'code' => 400, 'msg' => '请求地址不能为空!' ), JSON_UNESCAPED_UNICODE); }

// 初始化cURL
$curl = curl_init();
if ($curl === false) {
    return json_encode(array(
        'code' => 400,
        'msg' => '初始化失败,请重试!'
    ), JSON_UNESCAPED_UNICODE);
}

// 设置请求地址
$url = $config['url'];

// 处理请求参数
if (!empty($config['data']) && is_array($config['data'])) {
    if ($config['type'] == 0) {
        // GET请求:将参数拼接到URL
        $query_string = http_build_query($config['data']);
        $url .= (strpos($url, '?') === false ? '?' : '&') . $query_string;
    } else {
        // POST请求:设置POST数据
        $post_string = http_build_query($config['data']);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_string);
        
    }
}

// 设置基本选项
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, $config['curl_options']['return_transfer'] ?? true);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $config['curl_options']['connect_timeout'] ?? 10);
curl_setopt($curl, CURLOPT_TIMEOUT, $config['curl_options']['timeout'] ?? 30);

// SSL设置
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $config['curl_options']['ssl_verify_peer'] ?? false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $config['curl_options']['ssl_verify_host'] ?? false);

// 重定向设置
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, $config['curl_options']['follow_location'] ?? true);

// 编码设置
if (!empty($config['curl_options']['encoding'])) {
    curl_setopt($curl, CURLOPT_ENCODING, $config['curl_options']['encoding']);
}

// 代理设置
if (!empty($config['curl_options']['proxy'])) {
    curl_setopt($curl, CURLOPT_PROXY, $config['curl_options']['proxy']);
    curl_setopt($curl, CURLOPT_PROXYTYPE, $config['curl_options']['proxy_type'] ?? CURLPROXY_HTTP);
    
    // 代理认证
    if (!empty($config['curl_options']['proxy_auth']['username'])) {
        $auth = $config['curl_options']['proxy_auth']['username'] . ':' . 
                ($config['curl_options']['proxy_auth']['password'] ?? '');
        curl_setopt($curl, CURLOPT_PROXYUSERPWD, $auth);
    }
}

// 设置请求头
$headers = $config['headers'] ?? array();

// 如果单独设置了User-Agent,添加到请求头
if (!empty($config['user_agent'])) {
    $headers[] = 'User-Agent: ' . $config['user_agent'];
}

if (!empty($headers)) {
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
}

// 设置Cookie
if (!empty($config['cookie'])) {
    curl_setopt($curl, CURLOPT_COOKIE, $config['cookie']);
}

// 如果是POST请求但没有明确指定Content-Type,默认使用application/x-www-form-urlencoded
if ($config['type'] == 1) {
    $hasContentType = false;
    foreach ($headers as $header) {
        if (stripos($header, 'Content-Type:') !== false) {
            $hasContentType = true;
            break;
        }
    }
    
    if (!$hasContentType && is_array($config['data'])) {
        curl_setopt($curl, CURLOPT_HTTPHEADER, array_merge($headers, array(
            'Content-Type: application/x-www-form-urlencoded'
        )));
    }
}

// 执行请求
$response = curl_exec($curl);

// 错误处理
if ($response === false) {
    $error = curl_error($curl);
    $errno = curl_errno($curl);
    curl_close($curl);
    return json_encode(array(
        'code' => 400,
        'msg' => '请求失败: [{$errno}] {$error}'
    ), JSON_UNESCAPED_UNICODE);
}

// 获取HTTP状态码
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

// 获取请求信息(可选,可用于调试)
$info = array(
    'http_code' => $httpCode,
    'total_time' => curl_getinfo($curl, CURLINFO_TOTAL_TIME),
    'connect_time' => curl_getinfo($curl, CURLINFO_CONNECT_TIME),
    'effective_url' => curl_getinfo($curl, CURLINFO_EFFECTIVE_URL),
);

curl_close($curl);

// 可以根据需要返回info信息
// return array('info' => $info, 'response' => $response);

return $response;

} /* 本教程由接口盒子编辑 接口盒子:提供各种免费API接口,集群服务器保障服务稳定。 PHP通用GET/POST请求教程 */ ?> `