-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCurl.php
88 lines (82 loc) · 2 KB
/
Curl.php
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
<?PHP
/**
* curl库的封装
*/
class Su_Curl
{
protected $ch;
protected $url;
protected $lastInfo;
/**
* 构造函数
*/
public function __construct($url = null)
{
$this->url = $url;
$this->ch = curl_init($url);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->ch, CURLOPT_BINARYTRANSFER, true);
}
/**
* 设置curl选项
*/
public function setopt($type, $val)
{
curl_setopt($this->ch, $type, $val);
}
/**
* 发送post请求的快捷方法
*/
public function post($fields = null)
{
curl_setopt($this->ch, CURLOPT_POST, count($fields));
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($this->ch);
$this->lastInfo = curl_getinfo($this->ch);
return $result;
}
/**
* 发送get请求的快捷方法
*/
public function get($fields = null)
{
if (is_array($fields)) {
$info = curl_getinfo($this->ch);
$url = $info['url'] . '?' . http_build_query($fields);
curl_setopt($this->ch, CURLOPT_URL, $url);
}
$result = curl_exec($this->ch);
$this->lastInfo = curl_getinfo($this->ch);
return $result;
}
/**
* 接口请求处理,支持serialize&json
*/
public function rest($fields = null, $method = 'post', $format = null)
{
$data = $method == 'post' ? $this->post($fields) : $this->get($fields);
$data = preg_replace('/[^\x20-\xff]*/', '', $data); //清除不可见字符
$data = iconv('utf-8', 'utf-8//ignore', $data); //UTF-8转码
switch ($format) {
case Su_Const::FT_SERIAL :
if (false === ($result = unserialize($data))) {
throw new Su_Exc('unserialize error' . $data, $this->lastInfo['http_code']);
}
break;
case Su_Const::FT_JSON :
default :
if (false === ($result = json_decode($data, true))) {
throw new Su_Exc('json_decode error' . $data, $this->lastInfo['http_code']);
}
}
return $result;
}
/**
* 最后一次请求的信息记录
*/
public function lastInfo()
{
return $this->lastInfo;
}
}