Curl.php
2.22 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
<?php
/**
* curl类库
* Created by PhpStorm.
* User: DELL
* Date: 2016/6/16
* Time: 10:20
*/
namespace common\lib;
class Curl
{
/**
* GET方式网络请求
* @param $url
* @param array $data
* @param int $timeout
* @return mixed
*/
public static function get($url, array $data = array(), $timeout = 20)
{
$ch = curl_init(self::makeUrl($url, $data));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
/**
* post提交数据
* @param $url
* @param $data
* @param int $timeout
* @param array $header
* @param array $cookie
* @return mixed
*/
public static function post($url, $data, $timeout = 20, array $header = array(), array $cookie = array())
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
if (!empty($header)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);// array('Content-Type:application/json;charset=UTF-8'));
}
if (!empty($cookie)) {
$cookie_str = array();
foreach ($cookie as $key => $val) {
$cookie_str[] = urlencode($key) . '=' . urlencode($val);
}
curl_setopt($ch, CURLOPT_COOKIE, implode(';', $cookie_str));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
if (!empty($data)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
$result = curl_exec($ch);
// $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $result;
}
public static function makeUrl($url, array $data)
{
$params = '';
if (!empty($data)) {
$params = http_build_query($data, '', '&');
}
if (strpos($url, '?') === false) {
$url = $url . '?' . $params;
} else {
if (!empty($params)) {
$url = $url . '&' . $params;
}
}
return $url;
}
}