Curl.php
2.35 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
<?php
/**
* Created by PhpStorm.
* User: Zip
* Date: 14/12/22
* Time: 下午12:23
*/
namespace Hood\Concurrent\Http;
class Curl
{
/**
* GET方式网络请求
* @param $url
* @param array $data
* @param int $timeout
* @return mixed
*/
public static function get($url, array $data = array(), $timeout = 20)
{
$params = '';
if (!empty($data)) {
$params = http_build_query($data, '', '&');
}
if (strpos($url, '?') === false) {
if (!empty($params) && substr_compare($url, '/', -1)) {
$url = $url . '/?' . $params;
} else if (!empty($params)) {
$url = $url . '?' . $params;
}
} else {
if (!empty($params)) {
$url = $url . '&' . $params;
}
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
//$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
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;
}
}