iami233
iami233
文章153
标签38
分类4

文章分类

文章归档

PHP使用 CURL 发送网络请求

PHP使用 CURL 发送网络请求

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

CURL 函数

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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); // 注意:生产环境中最好启用 SSL 验证
curl_setopt($curl, CURLOPT_TIMEOUT, 5000);

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)) {
curl_close($curl);
return ''; // 处理可能的错误
}

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

curl_close($curl);
return $result;
}

请求示例

GET 请求

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

POST 请求

1
2
3
4
5
6
7
$url = "https://api.example.com/";
$data = [
'key1' => 'value1',
'key2' => 'value2'
];
$result = getCurl($url, $data);
echo $result;

自定义 HTTP 头部

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

接收 Set-Cookies

1
2
3
$url = "https://api.example.com/";
$result = getCurl($url, [], [], true);
echo $result;
本文作者:iami233
本文链接:https://5ime.cn/curl.html
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可