Curl.php
2.8 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
namespace jytools;
class Curl
{
// get 获取数据
static public function httpGet($url, $param = [], $header = [])
{
if (empty($url)) {
return false;
}
if (count($param) > 0) {
$url = $url . '?' . http_build_query($param);
}
$ch = curl_init();
$ch = self::curlSet($ch, $url, $header);
$output = curl_exec($ch);
if ($output === false) {
echo 'Curl error: ' . curl_error($ch);
}
curl_close($ch);
return $output;
}
//post 获取数据
static public function httpPost($url, $param = [], $header = [])
{
if (empty($url)) {
return false;
}
$ch = curl_init();
$ch = self::curlSet($ch, $url, $header);
$opts = [];
$opts[CURLOPT_POST] = 1;
$opts[CURLOPT_USERAGENT] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.98 Safari/537.36";
// 修改判断逻辑
$isJson = false;
foreach ($header as $h) {
if (stripos($h, 'Content-Type: application/json') !== false) {
$isJson = true;
break;
}
}
$opts[CURLOPT_POSTFIELDS] = $isJson ? json_encode($param) : http_build_query($param);
curl_setopt_array($ch, $opts);
$output = curl_exec($ch);
if ($output === false) {
echo 'Curl error: ' . curl_error($ch);
}
curl_close($ch);
return $output;
}
//delete 请求
static public function httpDelete($url, $param = [], $header = [])
{
if (empty($url)) {
return false;
}
if (count($param) > 0) {
$url = $url . '?' . http_build_query($param);
}
$ch = curl_init();
$ch = self::curlSet($ch, $url, $header);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
$output = curl_exec($ch);
if ($output === false) {
echo 'Curl error: ' . curl_error($ch);
}
curl_close($ch);
return $output;
}
//curl 参数设置
static private function curlSet($ch, $url, $header)
{
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, $url);
//参数为1表示传输数据,为0表示直接输出显示。
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//参数为0表示不带头文件,为1表示带头文件
curl_setopt($ch, CURLOPT_HEADER, 0);
if (!empty($header)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}
// 关闭SSL验证
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
return $ch;
}
}