PHP使用 CURL 发送网络请求

2 min read

最近在开发 短视频去水印 服务以及扩展 TenAPI 的接口数量时,我封装了一个 CURL 请求方法。这里记录并分享一下这个方法。

CURL 函数

以下是我封装的 getCurl 函数,它支持 GET 和 POST 请求,可以选择性地处理 cookies 和自定义 HTTP 头部。

function getCurl(string $url, array $data = [], array $headers = [], bool $includeCookies = false): string {
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_AUTOREFERER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_TIMEOUT, 30);
    
    if ($includeCookies) {
        curl_setopt($curl, CURLOPT_HEADER, true);
    }

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

    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }

    $result = curl_exec($curl);

    if (curl_errno($curl)) {
        $error = curl_error($curl);
        curl_close($curl);
        return 'Error: ' . $error;
    }

    if ($includeCookies) {
        preg_match('/Set-Cookie:(.*);/iU', $result, $str);
        $result = $str[1] ?? '';
    }

    curl_close($curl);
    return $result;
}

请求示例

GET 请求

$url = "https://api.example.com/";
$result = getCurl($url);
echo $result;

POST 请求

$url = "https://api.example.com/";
$data = [
    'key1' => 'value1',
    'key2' => 'value2'
];
$result = getCurl($url, $data);
echo $result;

自定义 HTTP 头部

$url = "https://api.example.com/";
$headers = [
    'Content-Type: application/json',
    'Authorization: Bearer YOUR_ACCESS_TOKEN'
];
$result = getCurl($url, [], $headers);
echo $result;

接收 Set-Cookies

$url = "https://api.example.com/";
$result = getCurl($url, [], [], true);
echo $result;