PHP-使用原生curl发送请求

Yaurora

PHP使用原生curl发送请求

简单请求

方法封装

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
37
function request_by_curl($url, $params = [], $method='GET', $headers = []){
$curl_options = [
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_URL => $url,
CURLOPT_CONNECTTIMEOUT => 3,
CURLOPT_TIMEOUT => 3,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => '',
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
];

if ($method == 'POST'){
$curl_options[CURLOPT_POST] = true;
if ($params){
$curl_options[CURLOPT_POSTFIELDS] = json_encode($params);
}
}else{
$curl_options[CURLOPT_CUSTOMREQUEST] = 'GET';
if ($params){
$querys = http_build_query($params);
$curl_options[CURLOPT_URL] = $url.'?'.$querys ;
}
}
$ch = curl_init();
curl_setopt_array($ch, $curl_options);
$result['response_data'] = curl_exec($ch);
$result['total_time'] = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
$result['connect_time'] = curl_getinfo($ch, CURLINFO_CONNECT_TIME);
$result['http_code'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$result['err_no'] = curl_errno($ch);
$result['err_msg'] = curl_error($ch);
curl_close($ch);
return $result;
}

方法调用

1
2
3
$url = "http://jsonplaceholder.typicode.com/posts";
$headers = ['Content-Type: application/json'];
$response = request_by_curl($url, [], $headers);

建议

​ 在调用三方的时候,尽量考虑添加超时时间,避免影响自己的业务

知识点

  • 标题: PHP-使用原生curl发送请求
  • 作者: Yaurora
  • 创建于 : 2023-12-10 16:30:12
  • 更新于 : 2023-12-25 23:43:44
  • 链接: https://jingyu.life/2023/12/10/common-codes/php_curl/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
此页目录
PHP-使用原生curl发送请求